Quellcode durchsuchen

feat(web): 优化深色聊天界面并支持 Markdown 渲染

gaoshutao vor 1 Monat
Ursprung
Commit
75963334cc

+ 39 - 0
scripts/check_frontend.py

@@ -0,0 +1,39 @@
+"""Serve isolated browser regression checks without the API, model or user data.
+
+Run `python scripts/check_frontend.py`, then open http://127.0.0.1:8081.
+Only a temporary copy of frontend assets is exposed. Ctrl+C stops the server.
+"""
+from functools import partial
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from tempfile import TemporaryDirectory
+import json
+import shutil
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+class Handler(SimpleHTTPRequestHandler):
+    def do_GET(self):
+        if self.path.startswith('/api/'):
+            body = json.dumps({'model': 'test', 'items': []}).encode()
+            self.send_response(200)
+            self.send_header('Content-Type', 'application/json')
+            self.end_headers()
+            self.wfile.write(body)
+        else:
+            super().do_GET()
+
+
+if __name__ == '__main__':
+    with TemporaryDirectory(prefix='deep-agent-frontend-') as directory:
+        shutil.copytree(ROOT / 'static', Path(directory) / 'static')
+        shutil.copyfile(ROOT / 'tests/frontend_markdown.html', Path(directory) / 'index.html')
+        server = ThreadingHTTPServer(('127.0.0.1', 8081), partial(Handler, directory=directory))
+        print('Frontend checks: http://127.0.0.1:8081', flush=True)
+        try:
+            server.serve_forever()
+        except KeyboardInterrupt:
+            pass
+        finally:
+            server.server_close()

+ 573 - 0
static/app.js

@@ -0,0 +1,573 @@
+
+const API = '/api';
+const USER = 'default';           // 2.0 无鉴权:这里自报身份
+let sessionId = null;
+let controller = null;
+let streaming = false;
+let resuming = false;
+let loadingHistory = false;
+let sessions = [];
+let pendingApproval = false;
+
+const el = (id) => document.getElementById(id);
+const log = el('log');
+
+function setStatus(text, state) {
+  el('statusPill').textContent = text;
+  el('statusPill').title = text;
+  el('statusDot').className = 'status-dot ' + (state || (streaming ? 'busy' : 'ready'));
+}
+
+function scrollDown() { const area = el('conversationScroll'); area.scrollTop = area.scrollHeight; }
+
+function addNode(cls, html) {
+  const wrap = document.createElement('div');
+  wrap.className = 'msg ' + cls;
+  wrap.innerHTML = html;
+  el('welcome').hidden = true;
+  log.appendChild(wrap);
+  scrollDown();
+  return wrap;
+}
+
+function addUserBubble(text) {
+  const node = addNode('user', '');
+  const b = document.createElement('div');
+  b.className = 'bubble';
+  b.textContent = text;
+  node.appendChild(b);
+  return node;
+}
+
+function newAssistant() {
+  const node = addNode('assistant', '');
+  const b = document.createElement('div');
+  b.className = 'bubble';
+  node.appendChild(b);
+  return { node, bubble: b, tools: {}, thinking: null, segment: null };
+}
+
+// Keep Markdown source separate from the rendered DOM. Each text segment owns
+// its timer, so a tool card cannot steal a pending update from the previous one.
+const markdownSegments = new WeakMap();
+
+function renderMarkdownSegment(segment) {
+  const state = markdownSegments.get(segment);
+  if (!state) return;
+  clearTimeout(state.timer);
+  state.timer = null;
+  if (!window.marked || !window.DOMPurify) {
+    segment.classList.add('plain-text');
+    segment.textContent = state.source;
+    return;
+  }
+  segment.classList.remove('plain-text');
+  const html = marked.parse(state.source, { gfm: true, breaks: true, async: false });
+  // Model output and stored history are untrusted. Sanitize before insertion.
+  const fragment = DOMPurify.sanitize(html, {
+    RETURN_DOM_FRAGMENT: true,
+    ALLOWED_TAGS: ['p', 'br', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'strong',
+      'em', 'del', 's', 'blockquote', 'ul', 'ol', 'li', 'pre', 'code', 'hr',
+      'a', 'img', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'input'],
+    ALLOWED_ATTR: ['href', 'title', 'src', 'alt', 'start', 'align', 'type', 'checked', 'disabled'],
+    ALLOW_DATA_ATTR: false,
+    ALLOW_ARIA_ATTR: false,
+  });
+  fragment.querySelectorAll('a').forEach((link) => {
+    link.target = '_blank';
+    link.rel = 'noopener noreferrer';
+  });
+  fragment.querySelectorAll('input').forEach((checkbox) => {
+    checkbox.type = 'checkbox';
+    checkbox.disabled = true;
+  });
+  fragment.querySelectorAll('table').forEach((table) => {
+    const wrapper = document.createElement('div');
+    wrapper.className = 'markdown-table';
+    wrapper.tabIndex = 0;
+    wrapper.setAttribute('role', 'region');
+    wrapper.setAttribute('aria-label', '表格,可横向滚动');
+    table.replaceWith(wrapper);
+    wrapper.appendChild(table);
+  });
+  segment.replaceChildren(fragment);
+}
+
+function appendToken(ui, text) {
+  if (!ui.segment) {
+    ui.segment = document.createElement('div');
+    ui.segment.className = 'segment';
+    ui.bubble.appendChild(ui.segment);
+    markdownSegments.set(ui.segment, { source: '', timer: null });
+  }
+  const segment = ui.segment;
+  const state = markdownSegments.get(segment);
+  state.source += text;
+  // Batch bursts of tokens rather than parsing the entire reply per token.
+  if (state.timer === null) {
+    state.timer = setTimeout(() => {
+      renderMarkdownSegment(segment);
+      if (segment.isConnected) scrollDown();
+    }, 50);
+  }
+}
+
+// Flush before adding tool/status cards to preserve chronological ordering.
+function breakSegment(ui) {
+  if (ui.segment) renderMarkdownSegment(ui.segment);
+  ui.segment = null;
+}
+
+function addCard(bubble, cls, title, body) {
+  const card = document.createElement('div');
+  card.className = 'card ' + cls;
+  const t = document.createElement('div');
+  t.className = 'title';
+  t.textContent = title;
+  card.appendChild(t);
+  if (body) {
+    const pre = document.createElement('pre');
+    pre.textContent = body;
+    card.appendChild(pre);
+  }
+  bubble.appendChild(card);
+  scrollDown();
+  return card;
+}
+
+function addCardFor(ui, cls, title, body) {
+  breakSegment(ui);
+  return addCard(ui.bubble, cls, title, body);
+}
+
+// ---------- 发送 ----------
+async function send() {
+  const input = el('input');
+  const text = input.value.trim();
+  if (!text || streaming || loadingHistory || pendingApproval) return;
+  const form = buildForm(text);
+  if (!sessionId) el('chatTitle').textContent = text.slice(0, 30);
+  const attachmentName = el('file').files[0]?.name;
+  input.value = '';
+  input.style.height = 'auto';
+  addUserBubble(text + (attachmentName ? '\n📎 ' + attachmentName : ''));
+  clearAttachment();
+  await stream(`${API}/chat`, 'POST', form);
+}
+
+function buildForm(text) {
+  const fd = new FormData();
+  fd.append('message', text);
+  if (sessionId) fd.append('session_id', sessionId);
+  fd.append('mode', el('mode').value);
+  fd.append('user_name', USER);
+  const f = el('file').files[0];
+  if (f) fd.append('file', f);
+  return fd;
+}
+
+function buildResumeBody(extra) {
+  return JSON.stringify(Object.assign({
+    session_id: sessionId, thread_id: sessionId, user_name: USER,
+  }, extra));
+}
+
+// ---------- 流式 ----------
+async function stream(url, method, body, isJson) {
+  const ui = newAssistant();
+  controller = new AbortController();
+  streaming = true;
+  updateControls();
+  setStatus('连接中...');
+
+  let citations = [];
+
+  try {
+    const headers = {};
+    if (isJson) headers['Content-Type'] = 'application/json';
+    const res = await fetch(url, { method, body, headers, signal: controller.signal });
+
+    if (!res.ok) {
+      let detail = '';
+      const raw = await res.text();
+      try { const parsed = JSON.parse(raw); detail = parsed.detail?.message || JSON.stringify(parsed.detail || parsed); } catch (e) { detail = raw; }
+      addCard(ui.bubble, 'error', `HTTP ${res.status}`, detail);
+      setStatus('请求失败', 'error');
+      return;
+    }
+    if (isJson) {
+      pendingApproval = false;
+      log.querySelectorAll('.approval .actions').forEach((row) => {
+        row.closest('.msg').dataset.resolved = 'true';
+        row.replaceWith(document.createTextNode('已提交确认'));
+      });
+    }
+    const sid = res.headers.get('X-Session-Id');
+    if (sid) { sessionId = sid; el('sessionPill').textContent = '会话:' + sid.slice(0, 8); }
+
+    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 { handle(JSON.parse(line.slice(6)), ui, citations); }
+        catch (e) { /* 半截 JSON,忽略 */ }
+      }
+    }
+    if (!ui.failed) setStatus(pendingApproval ? '等待你的确认' : '回复已完成', pendingApproval ? 'busy' : 'ready');
+  } catch (e) {
+    if (e.name === 'AbortError') {
+      addCard(ui.bubble, '', '已停止生成', '');
+      setStatus('已停止', 'ready');
+    } else {
+      addCard(ui.bubble, 'error', '连接中断,请重试', String(e));
+      setStatus('连接失败', 'error');
+    }
+  } finally {
+    breakSegment(ui);
+    scrollDown();
+    streaming = false;
+    controller = null;
+    updateControls();
+    loadSessions();
+  }
+}
+
+function handle(ev, ui, citations) {
+  switch (ev.type) {
+    case 'agent_start':
+      setStatus(`${ev.cn_agent || ev.agent} 已启动`);
+      break;
+    case 'thinking':
+      setStatus(ev.cn_agent ? `${ev.cn_agent}:${ev.message}` : ev.message);
+      break;
+    case 'thinking_token':
+      if (!ui.thinking) {
+        breakSegment(ui);
+        ui.thinking = document.createElement('details');
+        const s = document.createElement('summary');
+        s.textContent = '思考过程';
+        s.style.color = 'var(--fg-dim)';
+        ui.thinking.appendChild(s);
+        const p = document.createElement('pre');
+        p.style.fontSize = '12px';
+        p.style.color = 'var(--fg-dim)';
+        ui.thinking.appendChild(p);
+        ui.bubble.appendChild(ui.thinking);
+      }
+      ui.thinking.querySelector('pre').textContent += ev.content || '';
+      break;
+    case 'executing':
+      setStatus(ev.message || '执行中...');
+      if (ev.tools && ev.tools.length) {
+        const i = ev.tools.length - 1;
+        ui.tools[ev.tools[i]] = addCardFor(ui, 'pending', `调用 ${ev.cn_tools ? ev.cn_tools[i] : ev.tools[i]}`, '');
+      }
+      break;
+    case 'tool_call':
+      // 按 tool_call_id 索引:同一工具被调多次时按名字索引会把结果挂错卡
+      ui.tools[ev.tool_call_id || ev.tool] = addCardFor(ui, 'pending', `工具 ${ev.cn_tool || ev.tool}`, JSON.stringify(ev.args, null, 1));
+      break;
+    case 'tool_result': {
+      const key = ev.tool_call_id || ev.tool;
+      const card = ui.tools[key] || ui.tools[ev.tool];
+      const body = typeof ev.content === 'string' ? ev.content : JSON.stringify(ev.content, null, 1);
+      if (card) {
+        card.className = 'card ' + (ev.error ? 'error' : 'done');
+        const pre = document.createElement('pre'); pre.textContent = body; card.appendChild(pre);
+      } else {
+        addCardFor(ui, ev.error ? 'error' : 'done', `结果 ${ev.cn_tool || ev.tool}`, body);
+      }
+      break;
+    }
+    case 'updated_todo_list':
+      renderTodos(ui, ev.todos || []);
+      break;
+    case 'token':
+      appendToken(ui, ev.content || '');
+      break;
+    case 'citations':
+      citations.length = 0;
+      (ev.items || []).forEach((it) => citations.push(it));
+      renderCitations(ui, citations, ev.model_only);
+      break;
+    case 'interrupt':
+      pendingApproval = !!ev.tool_approval;
+      setStatus('等待你的确认', 'busy');
+      renderInterrupt(ui, ev);
+      break;
+    case 'agent_done':
+      setStatus(`完成 ${ev.duration_ms ? ev.duration_ms + 'ms' : ''} 上下文 ${ev.context_tokens || 0}/${ev.context_window || 0}`);
+      break;
+    case 'agent_error':
+    case 'error':
+      ui.failed = true;
+      setStatus('回复出错', 'error');
+      addCardFor(ui, 'error', `错误 [${ev.code || '-'}]`, ev.message || '');
+      break;
+    case 'done':
+      if (ev.usage) {
+        addCardFor(ui, '', '用量',
+          `输入 ${ev.usage.input_tokens} / 输出 ${ev.usage.output_tokens} / 合计 ${ev.usage.total_tokens}(${ev.usage.usage_source})`);
+      }
+      break;
+  }
+}
+
+function renderTodos(ui, todos) {
+  breakSegment(ui);
+  let card = ui.node.querySelector('.todos');
+  if (!card) {
+    card = document.createElement('div');
+    card.className = 'card todos';
+    ui.bubble.appendChild(card);
+  }
+  const mark = { completed: '[x]', in_progress: '[~]', pending: '[ ]' };
+  card.innerHTML = '<div class="title">待办</div>' +
+    todos.map((t) => `${mark[t.status] || '[ ]'} ${escapeHtml(t.content || '')}`).join('<br>');
+}
+
+function renderCitations(ui, items, modelOnly) {
+  breakSegment(ui);
+  const box = document.createElement('div');
+  box.className = 'card cite';
+  if (!items.length) {
+    box.textContent = modelOnly ? '本回答未引用外部数据源' : '无来源';
+  } else {
+    box.innerHTML = '<div class="title">来源(' + items.length + ')</div>' +
+      items.map((it, i) => {
+        const label = escapeHtml(it.title || it.url || '未命名');
+        const link = /^https?:\/\//i.test(it.url || '') ? ` <a href="${escapeAttr(it.url)}" target="_blank" rel="noreferrer">链接</a>` : '';
+        const score = (it.score !== undefined) ? ` <span style="color:var(--fg-dim)">score=${it.score}</span>` : '';
+        return `${i + 1}. ${label}${link}${score}`;
+      }).join('<br>');
+  }
+  ui.bubble.appendChild(box);
+  scrollDown();
+}
+
+function renderInterrupt(ui, ev) {
+  const ta = ev.tool_approval;
+  if (!ta) {
+    addCardFor(ui, 'approval', '智能体暂停', ev.message || '等待输入');
+    return;
+  }
+  const card = addCardFor(ui, 'approval',
+    `需确认:${ta.tool}`,
+    `${ta.reason || ''}\n${ta.side_effect || ''}\n\n参数:${JSON.stringify(ta.args, null, 1)}`);
+  const row = document.createElement('div');
+  row.className = 'actions';
+  const ok = document.createElement('button'); ok.className = 'ok'; ok.textContent = '批准';
+  const no = document.createElement('button'); no.className = 'no'; no.textContent = '拒绝';
+  const decide = async (extra) => {
+    if (streaming || resuming || ui.node.parentNode !== log) return;
+    ok.disabled = no.disabled = true;
+    await resume(extra, ui);
+    // Failed requests keep their original approval controls available for retry.
+    if (pendingApproval && !ui.node.dataset.resolved) ok.disabled = no.disabled = false;
+  };
+  ok.onclick = () => decide({ approved: true });
+  no.onclick = () => decide({ approved: false, status: 'cancelled' });
+  row.appendChild(ok); row.appendChild(no);
+  card.appendChild(row);
+}
+
+async function resume(extra, ui) {
+  // 双重保险:按钮点击后已经被 row.remove() 摘掉,这里再挡一次重复调用。
+  // 恢复请求重复发出会让图在同一 thread 上被 resume 两次,第二次必然失败。
+  if (streaming || resuming) return;
+  resuming = true;
+  setStatus('恢复中...');
+  try {
+    await stream(`${API}/chat/resume`, 'POST', buildResumeBody(extra), true);
+  } finally {
+    resuming = false;
+  }
+}
+
+function escapeHtml(s) {
+  return String(s).replace(/[&<>"']/g, (c) =>
+    ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+}
+function escapeAttr(s) { return escapeHtml(s).replace(/`/g, '&#96;'); }
+
+// ---------- 工作台交互 ----------
+function updateControls() {
+  const busy = streaming || loadingHistory;
+  el('sendBtn').disabled = busy || pendingApproval || !el('input').value.trim();
+  el('sendBtn').hidden = streaming;
+  el('stopBtn').disabled = !streaming;
+  el('stopBtn').hidden = !streaming;
+  el('newBtn').disabled = busy;
+  el('mode').disabled = busy || pendingApproval;
+  el('attachBtn').disabled = busy || pendingApproval;
+  el('removeFileBtn').disabled = busy;
+  document.querySelectorAll('.session-button').forEach((button) => { button.disabled = busy; });
+}
+
+function resizeInput() {
+  const input = el('input');
+  input.style.height = 'auto';
+  input.style.height = Math.min(input.scrollHeight, 160) + 'px';
+  updateControls();
+}
+
+function clearAttachment() {
+  el('file').value = '';
+  el('attachment').hidden = true;
+  el('fileName').textContent = '';
+}
+
+function toggleSidebar(open) {
+  el('sidebar').classList.toggle('open', open);
+  el('sidebarBackdrop').hidden = !open;
+  el('sidebarToggle').setAttribute('aria-expanded', String(open));
+  el('sidebarToggle').setAttribute('aria-label', open ? '收起会话列表' : '展开会话列表');
+}
+
+function renderSessions() {
+  const list = el('sessionList');
+  list.replaceChildren();
+  if (!sessions.length) {
+    const empty = document.createElement('p');
+    empty.className = 'list-empty';
+    empty.textContent = '还没有对话。开启新对话,记录你的每一个想法。';
+    list.appendChild(empty);
+  }
+  for (const session of sessions) {
+    const button = document.createElement('button');
+    button.className = 'session-button' + (session.id === sessionId ? ' active' : '');
+    button.setAttribute('aria-current', session.id === sessionId ? 'page' : 'false');
+    button.title = session.title || '未命名对话';
+    button.innerHTML = '<svg aria-hidden="true"><use href="#i-chat"/></svg><span></span>';
+    button.querySelector('span').textContent = (session.pinned ? '⌁ ' : '') + button.title;
+    button.onclick = () => openSession(session);
+    list.appendChild(button);
+  }
+  updateControls();
+}
+
+async function loadSessions() {
+  el('refreshBtn').disabled = true;
+  try {
+    const response = await fetch(`${API}/sessions?user_name=${encodeURIComponent(USER)}`);
+    if (!response.ok) throw new Error('会话列表加载失败');
+    const data = await response.json();
+    sessions = data.items || [];
+    renderSessions();
+  } catch (error) {
+    if (!sessions.length) {
+      const message = document.createElement('p');
+      message.className = 'list-empty';
+      message.textContent = '暂时无法加载对话,请点击刷新重试。';
+      el('sessionList').replaceChildren(message);
+    }
+  } finally { el('refreshBtn').disabled = false; }
+}
+
+async function openSession(session) {
+  if (streaming || loadingHistory || sessionId === session.id) return;
+  loadingHistory = true;
+  updateControls();
+  setStatus('正在加载对话', 'busy');
+  try {
+    const response = await fetch(`${API}/chat/history/${encodeURIComponent(session.id)}?user_name=${encodeURIComponent(USER)}&limit=500`);
+    if (!response.ok) throw new Error('无法加载这段对话,请重试');
+    const data = await response.json();
+    sessionId = session.id;
+    pendingApproval = false;
+    el('sessionPill').textContent = '会话:' + session.id.slice(0, 8);
+    el('chatTitle').textContent = session.title || '未命名对话';
+    el('mode').value = session.mode === 'plan' ? 'plan' : 'full';
+    el('input').value = '';
+    clearAttachment();
+    log.replaceChildren();
+    el('welcome').hidden = !!data.items.length;
+    for (const message of data.items) {
+      if (message.msg_role === 'user') addUserBubble(message.content);
+      else if (message.msg_role === 'assistant') {
+        const ui = newAssistant();
+        appendToken(ui, message.content || '');
+        breakSegment(ui);
+        if (Array.isArray(message.citations) && message.citations.length) renderCitations(ui, message.citations, false);
+      }
+    }
+    renderSessions();
+    toggleSidebar(false);
+    setStatus('对话已加载', 'ready');
+    try {
+      const response = await fetch(`${API}/chat/interrupt?session_id=${encodeURIComponent(sessionId)}&user_name=${encodeURIComponent(USER)}`);
+      if (!response.ok) throw new Error('确认状态读取失败');
+      if (response.status !== 204) {
+        const data = await response.json();
+        for (const event of data.interrupts || []) handle(event, newAssistant(), []);
+      }
+    } catch (error) { setStatus('对话已加载,确认状态获取失败', 'error'); }
+  } catch (error) {
+    setStatus(error.message, 'error');
+  } finally {
+    loadingHistory = false;
+    resizeInput();
+    scrollDown();
+  }
+}
+
+el('sendBtn').onclick = send;
+el('stopBtn').onclick = () => { if (controller) controller.abort(); };
+el('newBtn').onclick = () => {
+  if (streaming || loadingHistory) return;
+  sessionId = null;
+  pendingApproval = false;
+  el('sessionPill').textContent = '新会话';
+  el('chatTitle').textContent = '新对话';
+  el('input').value = '';
+  clearAttachment();
+  log.replaceChildren();
+  el('welcome').hidden = false;
+  setStatus('就绪', 'ready');
+  renderSessions();
+  resizeInput();
+  toggleSidebar(false);
+  el('input').focus();
+};
+el('input').addEventListener('keydown', (event) => {
+  if (event.key === 'Enter' && !event.shiftKey && !event.isComposing && event.keyCode !== 229) {
+    event.preventDefault();
+    send();
+  }
+});
+el('input').addEventListener('input', resizeInput);
+el('attachBtn').onclick = () => el('file').click();
+el('removeFileBtn').onclick = clearAttachment;
+el('file').addEventListener('change', () => {
+  const file = el('file').files[0];
+  el('attachment').hidden = !file;
+  el('fileName').textContent = file?.name || '';
+});
+el('refreshBtn').onclick = loadSessions;
+el('sidebarToggle').onclick = () => toggleSidebar(!el('sidebar').classList.contains('open'));
+el('sidebarBackdrop').onclick = () => { toggleSidebar(false); el('sidebarToggle').focus(); };
+document.addEventListener('keydown', (event) => {
+  if (event.key === 'Escape' && el('sidebar').classList.contains('open')) {
+    toggleSidebar(false); el('sidebarToggle').focus();
+  }
+});
+
+fetch(`${API}/model`).then((response) => {
+  if (!response.ok) throw new Error('服务不可达');
+  return response.json();
+}).then((data) => {
+  el('modelName').textContent = data.model || 'Deep Agent';
+  if (!streaming && !loadingHistory) setStatus('服务已就绪', 'ready');
+}).catch(() => {
+  el('modelName').textContent = '暂未连接模型';
+  if (!streaming && !loadingHistory) setStatus('服务不可达', 'error');
+});
+loadSessions();

+ 50 - 436
static/index.html

@@ -1,444 +1,58 @@
 <!DOCTYPE html>
 <html lang="zh-CN">
 <head>
-<meta charset="UTF-8" />
-<meta name="viewport" content="width=device-width, initial-scale=1.0" />
-<title>deep_agent 2.0 · 测试页</title>
-<style>
-  :root {
-    --bg: #0f1115; --panel: #171a21; --panel-2: #1e222b; --line: #2a2f3a;
-    --fg: #e6e9ef; --fg-dim: #98a1b3; --accent: #4f8cff; --ok: #34d399;
-    --warn: #fbbf24; --err: #f87171;
-  }
-  * { box-sizing: border-box; }
-  body {
-    margin: 0; background: var(--bg); color: var(--fg);
-    font: 14px/1.6 -apple-system, "Segoe UI", "Microsoft YaHei", sans-serif;
-    display: flex; flex-direction: column; height: 100vh;
-  }
-  header {
-    padding: 10px 16px; border-bottom: 1px solid var(--line);
-    display: flex; align-items: center; gap: 12px; flex-wrap: wrap;
-  }
-  header h1 { font-size: 15px; margin: 0; font-weight: 600; }
-  .spacer { flex: 1; }
-  .pill {
-    font-size: 12px; color: var(--fg-dim); background: var(--panel-2);
-    border: 1px solid var(--line); border-radius: 999px; padding: 2px 10px;
-  }
-  button {
-    background: var(--panel-2); color: var(--fg); border: 1px solid var(--line);
-    border-radius: 6px; padding: 5px 12px; cursor: pointer; font-size: 13px;
-  }
-  button:hover { border-color: var(--accent); }
-  button:disabled { opacity: .45; cursor: not-allowed; }
-  button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
-  button.ok { border-color: var(--ok); color: var(--ok); }
-  button.no { border-color: var(--err); color: var(--err); }
-  #log { flex: 1; overflow-y: auto; padding: 16px; display: flex; flex-direction: column; gap: 10px; }
-  .msg { max-width: 860px; width: 100%; margin: 0 auto; }
-  .msg.user { display: flex; justify-content: flex-end; }
-  .msg.user .bubble {
-    background: #24324a; border-radius: 10px 10px 2px 10px; padding: 8px 12px;
-    max-width: 75%; white-space: pre-wrap; word-break: break-word;
-  }
-  .msg.assistant .bubble {
-    background: var(--panel); border: 1px solid var(--line); border-radius: 10px;
-    padding: 10px 14px; word-break: break-word;
-  }
-  /* 正文文本段:每段对应「两次工具调用之间」模型说的话 */
-  .segment { white-space: pre-wrap; }
-  .segment + .segment { margin-top: 8px; }
-  .card {
-    border: 1px solid var(--line); background: var(--panel); border-radius: 8px;
-    padding: 8px 12px; margin: 6px 0; font-size: 13px;
-  }
-  .card .title { color: var(--fg-dim); font-size: 12px; margin-bottom: 4px; }
-  .card pre {
-    margin: 4px 0 0; font-size: 12px; color: var(--fg-dim);
-    white-space: pre-wrap; word-break: break-all; max-height: 160px; overflow: auto;
-  }
-  .card.pending { border-color: var(--warn); }
-  .card.done { border-color: var(--ok); }
-  .card.error { border-color: var(--err); }
-  .status { text-align: center; color: var(--fg-dim); font-size: 12px; padding: 4px; }
-  .approval { border-color: var(--warn); }
-  .approval .actions { display: flex; gap: 8px; margin-top: 8px; }
-  .cite { font-size: 12px; color: var(--fg-dim); }
-  .cite a { color: var(--accent); }
-  footer { border-top: 1px solid var(--line); padding: 10px 16px; }
-  .composer { max-width: 860px; margin: 0 auto; display: flex; gap: 8px; align-items: flex-end; }
-  textarea {
-    flex: 1; background: var(--panel); color: var(--fg); border: 1px solid var(--line);
-    border-radius: 8px; padding: 9px 12px; resize: none; font: inherit; min-height: 42px; max-height: 160px;
-  }
-  textarea:focus { outline: none; border-color: var(--accent); }
-  select, input[type=file] {
-    background: var(--panel); color: var(--fg-dim); border: 1px solid var(--line);
-    border-radius: 6px; padding: 5px; font-size: 12px;
-  }
-</style>
+  <meta charset="UTF-8" />
+  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+  <meta name="theme-color" content="#0f1115" />
+  <title>Deep Agent · 智能工作台</title>
+  <link rel="stylesheet" href="/static/styles.css?v=20260929-no-suggestions" />
+  <script src="/static/vendor/marked.umd.js" defer></script>
+  <script src="/static/vendor/purify.min.js" defer></script>
+  <script src="/static/app.js?v=20260929-no-suggestions" defer></script>
 </head>
 <body>
-<header>
-  <h1>deep_agent 2.0</h1>
-  <span class="pill" id="sessionPill">会话:新</span>
-  <span class="pill" id="statusPill">空闲</span>
-  <div class="spacer"></div>
-  <select id="mode" title="权限模式">
-    <option value="full">full(直接执行)</option>
-    <option value="plan">plan(先出计划)</option>
-  </select>
-  <input type="file" id="file" />
-  <button id="newBtn">新会话</button>
-</header>
-
-<div id="log"></div>
-
-<footer>
-  <div class="composer">
-    <textarea id="input" rows="1" placeholder="输入消息,Enter 发送 / Shift+Enter 换行。可用 #skill:demo-skill 前缀指定技能"></textarea>
-    <button class="primary" id="sendBtn">发送</button>
-    <button id="stopBtn" disabled>停止</button>
+<svg class="icon-library" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><defs>
+  <symbol id="i-mark" viewBox="0 0 24 24"><path d="m12 3 8 4.5v9L12 21l-8-4.5v-9L12 3Z"/><path d="m4 7.5 8 5 8-5M12 12.5V21M8 5.3l8 4.7v5"/></symbol>
+  <symbol id="i-plus" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></symbol>
+  <symbol id="i-chat" viewBox="0 0 24 24"><path d="M20 11.5a8 8 0 0 1-8 8H5l-3 2v-10a9 9 0 0 1 18 0Z"/><path d="M8 10h8M8 14h5"/></symbol>
+  <symbol id="i-arrow" viewBox="0 0 24 24"><path d="M12 19V5m-6 6 6-6 6 6"/></symbol>
+  <symbol id="i-paperclip" viewBox="0 0 24 24"><path d="m9 17 8-8a3 3 0 0 0-4-4L4 14a5 5 0 0 0 7 7l9-9a7 7 0 0 0-10-10L2 10" transform="translate(2 0) scale(.85)"/></symbol>
+  <symbol id="i-spark" viewBox="0 0 24 24"><path d="m12 3 2.5 6.5L21 12l-6.5 2.5L12 21l-2.5-6.5L3 12l6.5-2.5L12 3Z"/></symbol>
+  <symbol id="i-file" viewBox="0 0 24 24"><path d="M14 3H5v18h14V8l-5-5Zm0 0v6h5M8 13h8M8 17h5"/></symbol>
+  <symbol id="i-menu" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="16" rx="3"/><path d="M9 4v16"/></symbol>
+  <symbol id="i-close" viewBox="0 0 24 24"><path d="m6 6 12 12M6 18 18 6"/></symbol>
+</defs></svg>
+<button class="sidebar-backdrop" id="sidebarBackdrop" aria-label="关闭会话列表" hidden></button>
+<aside class="sidebar" id="sidebar" aria-label="会话导航">
+  <a class="brand" href="/" aria-label="Deep Agent 首页"><span class="brand-mark"><svg><use href="#i-mark"/></svg></span><span>Deep Agent <small>WORKSPACE</small></span><span class="version">2.0</span></a>
+  <button class="new-chat" id="newBtn"><svg><use href="#i-plus"/></svg>开启新对话<span class="new-hint">↗</span></button>
+  <div class="section-label">最近对话 <button class="text-button" id="refreshBtn" title="刷新对话列表" aria-label="刷新对话列表">刷新</button></div>
+  <nav class="session-list" id="sessionList" aria-label="最近对话"><p class="list-empty">正在加载对话…</p></nav>
+  <div class="sidebar-note"><span class="note-icon"><svg><use href="#i-spark"/></svg></span><strong>让想法更进一步</strong><p>从一个问题开始,<br>把复杂任务交给智能助手。</p></div>
+  <div class="profile"><div class="avatar">U</div><div><strong>默认工作空间</strong><span>个人工作台</span></div><span class="profile-dot" aria-hidden="true"></span></div>
+</aside>
+<main class="workspace">
+  <header class="topbar">
+    <div class="page-heading"><button class="icon-button" id="sidebarToggle" aria-label="展开会话列表" aria-controls="sidebar" aria-expanded="false"><svg><use href="#i-menu"/></svg></button><span class="breadcrumb">工作空间</span><span class="slash">/</span><h1 id="chatTitle">新对话</h1></div>
+    <div class="connection"><span class="status-dot" id="statusDot"></span><span id="statusPill" role="status">正在连接</span></div>
+  </header>
+  <div class="conversation-scroll" id="conversationScroll">
+    <section class="welcome" id="welcome" aria-labelledby="welcomeTitle">
+      <div class="eyebrow"><span></span> YOUR INTELLIGENT WORKSPACE</div>
+      <div class="welcome-mark"><svg><use href="#i-mark"/></svg><span class="little-spark">✦</span></div>
+      <h2 id="welcomeTitle">你好,今天想完成什么?</h2>
+      <p class="welcome-description">从灵感到行动,让复杂的工作变得简单。<br>提一个问题,或告诉我你想完成的任务。</p>
+    </section>
+    <div id="log" role="log" aria-label="对话内容" aria-live="polite" aria-relevant="additions"></div>
   </div>
-</footer>
-
-<script>
-const API = '/api';
-const USER = 'default';           // 2.0 无鉴权:这里自报身份
-let sessionId = null;
-let controller = null;
-let streaming = false;
-let resuming = false;
-
-const el = (id) => document.getElementById(id);
-const log = el('log');
-
-function setStatus(text) { el('statusPill').textContent = text; }
-
-function scrollDown() { log.scrollTop = log.scrollHeight; }
-
-function addNode(cls, html) {
-  const wrap = document.createElement('div');
-  wrap.className = 'msg ' + cls;
-  wrap.innerHTML = html;
-  log.appendChild(wrap);
-  scrollDown();
-  return wrap;
-}
-
-function addUserBubble(text) {
-  const node = addNode('user', '');
-  const b = document.createElement('div');
-  b.className = 'bubble';
-  b.textContent = text;
-  node.appendChild(b);
-  return node;
-}
-
-function newAssistant() {
-  const node = addNode('assistant', '');
-  const b = document.createElement('div');
-  b.className = 'bubble';
-  node.appendChild(b);
-  return { node, bubble: b, tools: {}, thinking: null, segment: null };
-}
-
-// 正文按「文本段」切分,与工具卡片按时间顺序交替排列。
-//
-// 为什么不能直接 `bubble.textContent += token`:读 textContent 会连子元素
-// (工具卡片)的文本一起读出来,赋值又会覆盖 bubble 的全部子节点——结果是
-// 卡片被抹平成一坨纯文本,且每次 append 都重新拼接全文(O(N²))。
-function appendToken(ui, text) {
-  if (!ui.segment) {
-    ui.segment = document.createElement('div');
-    ui.segment.className = 'segment';
-    ui.bubble.appendChild(ui.segment);
-  }
-  ui.segment.textContent += text;
-  scrollDown();
-}
-
-// 插入卡片时结束当前文本段,下一批 token 会另起一段,从而保留先后顺序
-function breakSegment(ui) {
-  ui.segment = null;
-}
-
-function addCard(bubble, cls, title, body) {
-  const card = document.createElement('div');
-  card.className = 'card ' + cls;
-  const t = document.createElement('div');
-  t.className = 'title';
-  t.textContent = title;
-  card.appendChild(t);
-  if (body) {
-    const pre = document.createElement('pre');
-    pre.textContent = body;
-    card.appendChild(pre);
-  }
-  bubble.appendChild(card);
-  scrollDown();
-  return card;
-}
-
-function addCardFor(ui, cls, title, body) {
-  breakSegment(ui);
-  return addCard(ui.bubble, cls, title, body);
-}
-
-// ---------- 发送 ----------
-async function send() {
-  const input = el('input');
-  const text = input.value.trim();
-  if (!text || streaming) return;
-  input.value = '';
-  input.style.height = 'auto';
-  addUserBubble(text);
-  await stream(`${API}/chat`, 'POST', buildForm(text));
-}
-
-function buildForm(text) {
-  const fd = new FormData();
-  fd.append('message', text);
-  if (sessionId) fd.append('session_id', sessionId);
-  fd.append('mode', el('mode').value);
-  fd.append('user_name', USER);
-  const f = el('file').files[0];
-  if (f) fd.append('file', f);
-  return fd;
-}
-
-function buildResumeBody(extra) {
-  return JSON.stringify(Object.assign({
-    session_id: sessionId, thread_id: sessionId, user_name: USER,
-  }, extra));
-}
-
-// ---------- 流式 ----------
-async function stream(url, method, body, isJson) {
-  const ui = newAssistant();
-  controller = new AbortController();
-  streaming = true;
-  el('sendBtn').disabled = true;
-  el('stopBtn').disabled = false;
-  setStatus('连接中...');
-
-  let citations = [];
-
-  try {
-    const headers = {};
-    if (isJson) headers['Content-Type'] = 'application/json';
-    const res = await fetch(url, { method, body, headers, signal: controller.signal });
-
-    if (!res.ok) {
-      let detail = '';
-      try { detail = JSON.stringify(await res.json()); } catch (e) { detail = await res.text(); }
-      addCard(ui.bubble, 'error', `HTTP ${res.status}`, detail);
-      setStatus('请求失败');
-      return;
-    }
-    const sid = res.headers.get('X-Session-Id');
-    if (sid) { sessionId = sid; el('sessionPill').textContent = '会话:' + sid.slice(0, 8); }
-
-    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 { handle(JSON.parse(line.slice(6)), ui, citations); }
-        catch (e) { /* 半截 JSON,忽略 */ }
-      }
-    }
-    setStatus('空闲');
-  } catch (e) {
-    if (e.name === 'AbortError') addCard(ui.bubble, '', '已停止', '');
-    else addCard(ui.bubble, 'error', '网络错误', String(e));
-    setStatus('空闲');
-  } finally {
-    streaming = false;
-    controller = null;
-    el('sendBtn').disabled = false;
-    el('stopBtn').disabled = true;
-  }
-}
-
-function handle(ev, ui, citations) {
-  switch (ev.type) {
-    case 'agent_start':
-      setStatus(`${ev.cn_agent || ev.agent} 已启动`);
-      break;
-    case 'thinking':
-      setStatus(ev.cn_agent ? `${ev.cn_agent}:${ev.message}` : ev.message);
-      break;
-    case 'thinking_token':
-      if (!ui.thinking) {
-        breakSegment(ui);
-        ui.thinking = document.createElement('details');
-        const s = document.createElement('summary');
-        s.textContent = '思考过程';
-        s.style.color = 'var(--fg-dim)';
-        ui.thinking.appendChild(s);
-        const p = document.createElement('pre');
-        p.style.fontSize = '12px';
-        p.style.color = 'var(--fg-dim)';
-        ui.thinking.appendChild(p);
-        ui.bubble.appendChild(ui.thinking);
-      }
-      ui.thinking.querySelector('pre').textContent += ev.content || '';
-      break;
-    case 'executing':
-      setStatus(ev.message || '执行中...');
-      if (ev.tools && ev.tools.length) {
-        const i = ev.tools.length - 1;
-        ui.tools[ev.tools[i]] = addCardFor(ui, 'pending', `调用 ${ev.cn_tools ? ev.cn_tools[i] : ev.tools[i]}`, '');
-      }
-      break;
-    case 'tool_call':
-      // 按 tool_call_id 索引:同一工具被调多次时按名字索引会把结果挂错卡
-      ui.tools[ev.tool_call_id || ev.tool] = addCardFor(ui, 'pending', `工具 ${ev.cn_tool || ev.tool}`, JSON.stringify(ev.args, null, 1));
-      break;
-    case 'tool_result': {
-      const key = ev.tool_call_id || ev.tool;
-      const card = ui.tools[key] || ui.tools[ev.tool];
-      const body = typeof ev.content === 'string' ? ev.content : JSON.stringify(ev.content, null, 1);
-      if (card) {
-        card.className = 'card ' + (ev.error ? 'error' : 'done');
-        const pre = document.createElement('pre'); pre.textContent = body; card.appendChild(pre);
-      } else {
-        addCardFor(ui, ev.error ? 'error' : 'done', `结果 ${ev.cn_tool || ev.tool}`, body);
-      }
-      break;
-    }
-    case 'updated_todo_list':
-      renderTodos(ui, ev.todos || []);
-      break;
-    case 'token':
-      appendToken(ui, ev.content || '');
-      break;
-    case 'citations':
-      citations.length = 0;
-      (ev.items || []).forEach((it) => citations.push(it));
-      renderCitations(ui, citations, ev.model_only);
-      break;
-    case 'interrupt':
-      setStatus('等待人工确认');
-      renderInterrupt(ui, ev);
-      break;
-    case 'agent_done':
-      setStatus(`完成 ${ev.duration_ms ? ev.duration_ms + 'ms' : ''} 上下文 ${ev.context_tokens || 0}/${ev.context_window || 0}`);
-      break;
-    case 'error':
-      setStatus('出错');
-      addCardFor(ui, 'error', `错误 [${ev.code || '-'}]`, ev.message || '');
-      break;
-    case 'done':
-      if (ev.usage) {
-        addCardFor(ui, '', '用量',
-          `输入 ${ev.usage.input_tokens} / 输出 ${ev.usage.output_tokens} / 合计 ${ev.usage.total_tokens}(${ev.usage.usage_source})`);
-      }
-      break;
-  }
-}
-
-function renderTodos(ui, todos) {
-  breakSegment(ui);
-  let card = ui.node.querySelector('.todos');
-  if (!card) {
-    card = document.createElement('div');
-    card.className = 'card todos';
-    ui.bubble.appendChild(card);
-  }
-  const mark = { completed: '[x]', in_progress: '[~]', pending: '[ ]' };
-  card.innerHTML = '<div class="title">待办</div>' +
-    todos.map((t) => `${mark[t.status] || '[ ]'} ${escapeHtml(t.content || '')}`).join('<br>');
-}
-
-function renderCitations(ui, items, modelOnly) {
-  breakSegment(ui);
-  const box = document.createElement('div');
-  box.className = 'card cite';
-  if (!items.length) {
-    box.textContent = modelOnly ? '本回答未引用外部数据源' : '无来源';
-  } else {
-    box.innerHTML = '<div class="title">来源(' + items.length + ')</div>' +
-      items.map((it, i) => {
-        const label = escapeHtml(it.title || it.url || '未命名');
-        const link = it.url ? ` <a href="${escapeAttr(it.url)}" target="_blank" rel="noreferrer">链接</a>` : '';
-        const score = (it.score !== undefined) ? ` <span style="color:var(--fg-dim)">score=${it.score}</span>` : '';
-        return `${i + 1}. ${label}${link}${score}`;
-      }).join('<br>');
-  }
-  ui.bubble.appendChild(box);
-  scrollDown();
-}
-
-function renderInterrupt(ui, ev) {
-  const ta = ev.tool_approval;
-  if (!ta) {
-    addCardFor(ui, 'approval', '智能体暂停', ev.message || '等待输入');
-    return;
-  }
-  const card = addCardFor(ui, 'approval',
-    `需确认:${ta.tool}`,
-    `${ta.reason || ''}\n${ta.side_effect || ''}\n\n参数:${JSON.stringify(ta.args, null, 1)}`);
-  const row = document.createElement('div');
-  row.className = 'actions';
-  const ok = document.createElement('button'); ok.className = 'ok'; ok.textContent = '批准';
-  const no = document.createElement('button'); no.className = 'no'; no.textContent = '拒绝';
-  ok.onclick = () => { row.remove(); resume({ approved: true }, ui); };
-  no.onclick = () => { row.remove(); resume({ approved: false, status: 'cancelled' }, ui); };
-  row.appendChild(ok); row.appendChild(no);
-  card.appendChild(row);
-}
-
-async function resume(extra, ui) {
-  // 双重保险:按钮点击后已经被 row.remove() 摘掉,这里再挡一次重复调用。
-  // 恢复请求重复发出会让图在同一 thread 上被 resume 两次,第二次必然失败。
-  if (streaming || resuming) return;
-  resuming = true;
-  setStatus('恢复中...');
-  try {
-    await stream(`${API}/chat/resume`, 'POST', buildResumeBody(extra), true);
-  } finally {
-    resuming = false;
-  }
-}
-
-function escapeHtml(s) {
-  return String(s).replace(/[&<>"']/g, (c) =>
-    ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
-}
-function escapeAttr(s) { return escapeHtml(s).replace(/`/g, '&#96;'); }
-
-// ---------- 交互 ----------
-el('sendBtn').onclick = send;
-el('stopBtn').onclick = () => { if (controller) controller.abort(); };
-el('newBtn').onclick = () => {
-  if (streaming) return;
-  sessionId = null;
-  el('sessionPill').textContent = '会话:新';
-  log.innerHTML = '';
-  setStatus('空闲');
-};
-el('input').addEventListener('keydown', (e) => {
-  if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
-});
-el('input').addEventListener('input', (e) => {
-  e.target.style.height = 'auto';
-  e.target.style.height = Math.min(e.target.scrollHeight, 160) + 'px';
-});
-
-// 加载时探一下服务是否就绪
-fetch(`${API}/model`).then((r) => r.json())
-  .then((d) => setStatus(`就绪 · ${d.model}`))
-  .catch(() => setStatus('服务不可达'));
-</script>
+  <footer class="composer-area">
+    <div class="composer">
+      <div class="attachment" id="attachment" hidden><svg><use href="#i-file"/></svg><span id="fileName"></span><button class="icon-button" id="removeFileBtn" aria-label="移除附件"><svg><use href="#i-close"/></svg></button></div>
+      <textarea id="input" rows="2" aria-label="输入消息" placeholder="有什么想法?告诉我,我们一起完成。"></textarea>
+      <div class="composer-toolbar"><div class="composer-options"><input type="file" id="file" hidden /><button class="icon-button" id="attachBtn" title="添加附件" aria-label="添加附件"><svg><use href="#i-paperclip"/></svg></button><span class="toolbar-divider"></span><label class="mode-select"><svg><use href="#i-spark"/></svg><select id="mode" aria-label="执行模式" title="直接执行任务,或先制定计划"><option value="full">直接执行</option><option value="plan">先出计划</option></select></label></div><div class="send-actions"><span class="keyboard-hint">Enter 发送</span><button id="stopBtn" class="stop-button" hidden disabled><span></span>停止</button><button class="send-button" id="sendBtn" aria-label="发送消息" title="发送消息" disabled><svg><use href="#i-arrow"/></svg></button></div></div>
+    </div>
+    <div class="composer-meta"><span><span class="mini-dot"></span><span id="modelName">正在获取模型</span></span><span class="desktop-hint">Shift + Enter 换行 · 内容由 AI 生成,请核实重要信息</span><span id="sessionPill">新会话</span></div>
+  </footer>
+</main>
 </body>
 </html>

+ 149 - 0
static/styles.css

@@ -0,0 +1,149 @@
+/* Original dark palette, shared by the workspace and Markdown content. */
+:root {
+  color-scheme: dark;
+  --bg: #0f1115; --panel: #171a21; --panel-2: #1e222b; --line: #2a2f3a;
+  --fg: #e6e9ef; --fg-dim: #98a1b3; --accent: #4f8cff;
+  --ok: #34d399; --warn: #fbbf24; --err: #f87171;
+  --muted: #7e899d; --accent-soft: #24324a; --accent-line: #354d73;
+}
+* { box-sizing: border-box; }
+[hidden] { display: none !important; }
+body { margin: 0; background: var(--bg); color: var(--fg); font: 14px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; display: flex; height: 100vh; height: 100dvh; overflow: hidden; }
+button, textarea, select { font: inherit; }
+button, a, select, textarea { -webkit-tap-highlight-color: transparent; }
+button { cursor: pointer; color: inherit; background: transparent; border: 0; transition: background .18s, border-color .18s, transform .18s, box-shadow .18s; }
+button:disabled { cursor: not-allowed; opacity: .45; }
+button:focus-visible, a:focus-visible, select:focus-visible, textarea:focus-visible { outline: 2px solid var(--accent); outline-offset: 4px; }
+a { color: var(--accent); }
+svg { width: 20px; height: 20px; fill: none; stroke: currentColor; stroke-width: 1.65; stroke-linecap: round; stroke-linejoin: round; flex-shrink: 0; }
+.icon-library { position: absolute; width: 0; height: 0; overflow: hidden; }
+.sidebar { width: 258px; flex-shrink: 0; padding: 32px 20px 18px; background: var(--panel); border-right: 1px solid var(--line); display: flex; flex-direction: column; }
+.brand { display: flex; align-items: center; gap: 10px; margin: 0 6px 35px; color: var(--fg); text-decoration: none; font-size: 19px; font-weight: 650; letter-spacing: -.5px; line-height: 1.25; }
+.brand-mark { background: var(--accent); color: #fff; border-radius: 11px; width: 37px; height: 40px; display: grid; place-items: center; }
+.brand-mark svg { width: 26px; height: 26px; }
+.brand small { display: block; font-size: 8px; letter-spacing: 2.5px; margin-top: 6px; color: var(--fg-dim); font-weight: 500; }
+.version { font-size: 10px; padding: 2px 5px; background: var(--panel-2); border: 1px solid var(--line); border-radius: 5px; margin-left: auto; letter-spacing: 0; align-self: flex-start; }
+.new-chat { display: flex; align-items: center; gap: 11px; width: 100%; padding: 12px 15px; border: 1px solid var(--accent-line); border-radius: 9px; background: var(--accent-soft); color: #b8d0ff; font-weight: 550; }
+.new-chat:hover { background: #2d4060; border-color: var(--accent); }
+.new-hint { margin-left: auto; font-size: 19px; font-weight: 400; color: var(--accent); }
+.section-label { font-size: 11px; color: var(--fg-dim); letter-spacing: 1px; margin: 32px 10px 12px; display: flex; align-items: center; justify-content: space-between; }
+.text-button { font-size: 11px; color: var(--fg-dim); padding: 3px; }
+.text-button:hover { color: var(--accent); }
+.session-list { flex: 1; min-height: 90px; overflow: auto; }
+.list-empty { color: var(--fg-dim); font-size: 12px; padding: 8px 10px; line-height: 1.9; }
+.session-button { display: flex; gap: 10px; width: 100%; text-align: left; padding: 11px 10px; border-radius: 7px; color: var(--fg-dim); font-size: 12px; margin: 3px 0; align-items: center; }
+.session-button svg { width: 16px; height: 16px; opacity: .7; }
+.session-button span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.session-button:hover, .session-button.active { background: var(--accent-soft); color: #b8d0ff; }
+.sidebar-note { border: 1px solid var(--line); border-radius: 10px; padding: 17px; margin: 22px 2px; background: linear-gradient(120deg, var(--panel-2), var(--panel)); }
+.note-icon { display: block; color: var(--accent); margin-bottom: 6px; }
+.sidebar-note strong { font-size: 12px; font-weight: 550; }
+.sidebar-note p { font-size: 11px; color: var(--fg-dim); line-height: 1.9; margin: 6px 0 0; }
+.profile { border-top: 1px solid var(--line); display: flex; align-items: center; gap: 10px; padding: 20px 8px 0; }
+.avatar { width: 33px; height: 33px; border: 1px solid var(--line); background: var(--panel-2); border-radius: 50%; display: grid; place-items: center; font-size: 12px; color: var(--fg-dim); }
+.profile strong, .profile span:not(.profile-dot) { display: block; font-size: 11px; font-weight: 500; }
+.profile span:not(.profile-dot) { font-size: 10px; color: var(--muted); margin-top: 2px; }
+.profile-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--ok); margin-left: auto; }
+.workspace { flex: 1; min-width: 0; display: flex; flex-direction: column; position: relative; }
+.topbar { height: 79px; flex-shrink: 0; padding: 0 38px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--line); gap: 18px; }
+.page-heading { display: flex; align-items: center; gap: 15px; min-width: 0; font-size: 12px; }
+.breadcrumb { color: var(--fg-dim); white-space: nowrap; }
+.slash { color: var(--muted); }
+h1 { font-size: 12px; font-weight: 500; margin: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 280px; }
+.connection { display: flex; align-items: center; gap: 7px; color: var(--fg-dim); font-size: 11px; min-width: 0; }
+#statusPill { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 260px; }
+.status-dot, .mini-dot { height: 6px; width: 6px; background: var(--muted); border-radius: 50%; display: inline-block; flex-shrink: 0; }
+.status-dot.ready { background: var(--ok); box-shadow: 0 0 0 3px #34d39918; }
+.status-dot.busy { background: var(--warn); animation: pulse 1.3s ease-in-out infinite; }
+.status-dot.error { background: var(--err); }
+.conversation-scroll { flex: 1; min-height: 0; overflow-y: auto; padding: 0 40px; scrollbar-width: thin; scrollbar-color: var(--line) transparent; }
+.welcome { max-width: 790px; margin: auto; padding: clamp(36px, 7vh, 85px) 0 28px; text-align: center; }
+.eyebrow { color: var(--fg-dim); font-size: 9px; letter-spacing: 2.3px; display: flex; gap: 7px; align-items: center; justify-content: center; }
+.eyebrow span { width: 4px; height: 4px; background: var(--accent); border-radius: 50%; }
+.welcome-mark { position: relative; width: 64px; height: 64px; border: 1px solid var(--accent-line); border-radius: 20px; margin: 24px auto 22px; display: grid; place-items: center; color: #92b8ff; background: linear-gradient(140deg, #263853, var(--panel-2)); box-shadow: 0 8px 23px #00000026, inset 0 1px 0 #ffffff0a; transform: rotate(-7deg); }
+.welcome-mark svg { width: 37px; height: 37px; stroke-width: 1.3; transform: rotate(7deg); }
+.little-spark { position: absolute; right: -9px; top: -14px; font-size: 23px; color: var(--accent); }
+h2 { font-size: clamp(25px, 2.6vw, 35px); line-height: 1.4; margin: 0; font-weight: 560; letter-spacing: -1px; color: var(--fg); }
+.welcome-description { font-size: 13px; color: var(--fg-dim); margin: 16px 0 39px; line-height: 1.95; }
+
+#log { max-width: 790px; margin: 0 auto; padding: 28px 0 16px; display: flex; flex-direction: column; gap: 26px; }
+#log:empty { display: none; }
+.msg { width: 100%; min-width: 0; }.msg.user { display: flex; justify-content: flex-end; }
+.msg.user .bubble { background: var(--accent-soft); color: var(--fg); border: 1px solid var(--accent-line); border-radius: 16px 16px 4px 16px; padding: 12px 17px; max-width: 82%; white-space: pre-wrap; overflow-wrap: anywhere; }
+.msg.assistant::before { content: "✧  Deep Agent"; display: block; color: #92b8ff; font-size: 11px; font-weight: 600; letter-spacing: .3px; margin-bottom: 10px; }
+.msg.assistant .bubble { background: var(--panel); border: 1px solid var(--line); border-radius: 4px 14px 14px 14px; padding: 20px 22px; overflow-wrap: anywhere; line-height: 1.9; }
+.segment { white-space: normal; min-width: 0; }
+.segment.plain-text { white-space: pre-wrap; }.segment + .segment { margin-top: 12px; }
+.card { border: 1px solid var(--line); background: var(--panel-2); border-radius: 8px; padding: 10px 13px; margin: 10px 0; font-size: 12px; }
+.card .title { color: var(--fg-dim); font-size: 11px; margin-bottom: 4px; font-weight: 550; }
+pre { white-space: pre-wrap; overflow-wrap: anywhere; }
+.card pre { margin: 4px 0 0; font-size: 11px; color: var(--fg-dim); max-height: 180px; overflow: auto; line-height: 1.7; }
+.card.pending, .card.approval { border-left: 3px solid var(--warn); background: #29251b; }.card.done { border-left: 3px solid var(--ok); }.card.error { border-left: 3px solid var(--err); background: #2b1e23; }
+.approval .actions { display: flex; gap: 8px; margin-top: 12px; }.actions button { border: 1px solid var(--line); border-radius: 6px; padding: 5px 16px; background: var(--panel); }.actions button.ok { color: var(--ok); border-color: #34d39955; }.actions button.no { color: var(--err); }
+.cite { font-size: 11px; color: var(--fg-dim); }.cite a { margin: 0 5px; }
+details summary { cursor: pointer; font-size: 12px; }.status { text-align: center; color: var(--fg-dim); font-size: 12px; }
+.composer-area { padding: 20px 40px 23px; background: var(--bg); }
+.composer { max-width: 790px; margin: auto; border: 1px solid var(--line); border-radius: 16px; padding: 17px 18px 12px; background: var(--panel); box-shadow: 0 7px 28px #00000026, 0 2px 6px #00000014; transition: border-color .2s, box-shadow .2s; }
+.composer:focus-within { border-color: var(--accent); box-shadow: 0 0 0 3px #4f8cff14, 0 7px 28px #00000026; }
+textarea { width: 100%; border: 0; outline: none !important; resize: none; background: transparent; color: var(--fg); padding: 2px 2px 10px; font-size: 13px; line-height: 1.7; min-height: 65px; max-height: 160px; }
+textarea::placeholder { color: var(--muted); }
+.composer-toolbar, .composer-options, .send-actions { display: flex; align-items: center; gap: 12px; }.composer-toolbar { justify-content: space-between; }
+.icon-button { display: inline-grid; place-items: center; width: 32px; height: 32px; border-radius: 7px; color: var(--fg-dim); flex-shrink: 0; }.icon-button:hover { background: var(--panel-2); color: var(--accent); }
+.toolbar-divider { width: 1px; height: 15px; background: var(--line); }
+.mode-select { display: flex; align-items: center; gap: 4px; color: var(--fg-dim); }.mode-select svg { width: 14px; height: 14px; }.mode-select select { color: var(--fg-dim); border: 0; background: transparent; font-size: 11px; cursor: pointer; max-width: 110px; padding: 5px 0; }
+.keyboard-hint { font-size: 10px; color: var(--muted); }.send-button { width: 34px; height: 34px; display: grid; place-items: center; color: #fff; background: var(--accent); border-radius: 10px; }.send-button:hover:not(:disabled) { background: #679cff; transform: translateY(-1px); }.send-button:disabled { opacity: 1; background: var(--panel-2); color: var(--muted); }
+.stop-button { display: flex; align-items: center; gap: 7px; border-radius: 8px; padding: 7px 11px; background: #f8717118; color: var(--err); font-size: 11px; }.stop-button span { width: 9px; height: 9px; border-radius: 2px; background: currentColor; }
+.composer-meta { max-width: 790px; margin: 13px auto 0; display: flex; justify-content: space-between; align-items: center; gap: 10px; color: var(--muted); font-size: 9px; }.composer-meta > span:first-child { display: flex; align-items: center; gap: 6px; }.mini-dot { width: 4px; height: 4px; background: var(--muted); }
+.attachment { display: flex; align-items: center; gap: 8px; border: 1px solid var(--line); padding: 3px 8px; border-radius: 8px; width: fit-content; max-width: 100%; background: var(--panel-2); margin-bottom: 12px; font-size: 11px; }.attachment > svg { width: 16px; height: 16px; }#fileName { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+#sidebarToggle { display: none; }.sidebar-backdrop { position: fixed; inset: 0; background: #00000088; z-index: 5; }
+@keyframes pulse { 50% { opacity: .35; } }
+@media (min-width: 1500px) { .welcome { padding-top: 10vh; } }
+@media (max-width: 1100px) { .sidebar { width: 224px; padding-inline: 15px; }.brand { font-size: 17px; }.brand small { font-size: 7px; }.topbar { padding-inline: 26px; }.conversation-scroll { padding-inline: 28px; }.composer-area { padding-inline: 28px; }.desktop-hint { display: none; } }
+@media (max-width: 800px) { .sidebar { position: fixed; left: 0; top: 0; bottom: 0; z-index: 6; width: 258px; visibility: hidden; transform: translateX(-100%); transition: transform .2s; }.sidebar.open { visibility: visible; transform: translateX(0); }#sidebarToggle { display: inline-grid; }.topbar { height: 65px; padding-inline: 18px; }.page-heading { gap: 10px; }.breadcrumb, .slash { display: none; }h1 { max-width: 200px; }.connection { max-width: 40%; }.welcome { padding-top: 42px; }.welcome-description { margin-bottom: 27px; }.conversation-scroll { padding-inline: 24px; }.composer-area { padding: 14px 24px max(16px, env(safe-area-inset-bottom)); } }
+@media (max-width: 440px) { .topbar { padding-inline: 12px; }h1 { max-width: 140px; }.conversation-scroll { padding-inline: 18px; }.welcome { padding-top: 30px; }.welcome-mark { margin-top: 20px; margin-bottom: 20px; }.eyebrow { font-size: 8px; letter-spacing: 1.6px; }h2 { font-size: 25px; }.welcome-description { font-size: 12px; }.composer-area { padding-inline: 14px; }.composer { padding: 13px 12px 10px; }.keyboard-hint { display: none; }.msg.assistant .bubble { padding: 15px; } }
+@media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation: none !important; transition: none !important; } }
+/* Compact welcome spacing on common laptop screens. */
+@media (min-width: 801px) and (max-height: 800px) {
+  .welcome { padding-top: 25px; padding-bottom: 16px; }
+  .welcome-mark { width: 54px; height: 54px; margin: 16px auto; border-radius: 17px; }
+  .welcome-mark svg { width: 32px; height: 32px; }
+  .welcome-description { margin: 12px 0 22px; }
+
+}
+
+/* Markdown typography is scoped so message headings do not inherit the topbar. */
+.segment { font-size: 14px; line-height: 1.8; overflow-wrap: anywhere; }
+.segment > :first-child { margin-top: 0; }
+.segment > :last-child { margin-bottom: 0; }
+.segment p { margin: 0 0 12px; }
+.segment h1, .segment h2, .segment h3, .segment h4, .segment h5, .segment h6 {
+  color: var(--fg); font-weight: 650; line-height: 1.45; letter-spacing: 0;
+  margin: 22px 0 12px; max-width: none; white-space: normal; overflow: visible;
+}
+.segment h1 { font-size: 25px; }
+.segment h2 { font-size: 21px; }
+.segment h3 { font-size: 18px; }
+.segment h4, .segment h5, .segment h6 { font-size: 15px; }
+.segment ul, .segment ol { margin: 8px 0 14px; padding-left: 25px; }
+.segment li { margin: 5px 0; padding-left: 2px; }
+.segment li > p { margin-bottom: 6px; }
+.segment li > ul, .segment li > ol { margin-block: 4px; }
+.segment li input { margin-right: 7px; accent-color: var(--accent); }
+.segment blockquote { margin: 14px 0; padding: 9px 15px; border-left: 3px solid var(--accent); color: var(--fg-dim); background: var(--panel-2); border-radius: 0 6px 6px 0; }
+.segment blockquote > :last-child { margin-bottom: 0; }
+.segment code { font: .9em/1.6 ui-monospace, SFMono-Regular, Consolas, "Liberation Mono", monospace; background: var(--panel-2); color: #bfd4ff; border-radius: 4px; padding: 2px 5px; }
+.segment pre { margin: 14px 0; padding: 15px 17px; border: 1px solid var(--line); border-radius: 9px; background: var(--bg); white-space: pre; overflow: auto; overflow-wrap: normal; tab-size: 2; }
+.segment pre code { display: block; padding: 0; color: var(--fg); background: transparent; border-radius: 0; font-size: 12px; white-space: pre; }
+.segment a { color: #82afff; text-decoration: underline; text-underline-offset: 3px; }
+.segment a:hover { color: #b7d0ff; }
+.segment hr { border: 0; border-top: 1px solid var(--line); margin: 20px 0; }
+.segment img { max-width: 100%; height: auto; border-radius: 8px; }
+.markdown-table { max-width: 100%; overflow-x: auto; margin: 14px 0; border: 1px solid var(--line); border-radius: 8px; scrollbar-width: thin; }
+.segment table { border-collapse: collapse; width: 100%; font-size: 13px; }
+.segment th, .segment td { padding: 9px 13px; text-align: left; border-bottom: 1px solid var(--line); border-right: 1px solid var(--line); min-width: 90px; }
+.segment th { background: var(--panel-2); font-weight: 600; }
+.segment th[align="center"], .segment td[align="center"] { text-align: center; }
+.segment th[align="right"], .segment td[align="right"] { text-align: right; }
+.segment tr:last-child td { border-bottom: 0; }
+.segment th:last-child, .segment td:last-child { border-right: 0; }
+.segment tbody tr:nth-child(even) { background: #ffffff03; }

+ 11 - 0
static/vendor/README.md

@@ -0,0 +1,11 @@
+# Browser dependencies
+
+Pinned browser distributions served locally; no CDN is needed at runtime.
+
+- marked 18.0.14: `marked.umd.js`; [source](https://registry.npmjs.org/marked/-/marked-18.0.14.tgz); license: `marked.LICENSE`.
+  npm archive integrity: `sha512-mBHK6FBHuBAlhgRe88w9F0O1AbwwXJUcQibUbC/QcdTbVGAD7aWza+xt3N6oT/jCZx3/OMeS+8rnuiHZcQ9s7A==`
+
+- dompurify 3.4.16: `purify.min.js`; [source](https://registry.npmjs.org/dompurify/-/dompurify-3.4.16.tgz); license: `dompurify.LICENSE`.
+  npm archive integrity: `sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ==`
+
+Downloaded from the npm registry and verified against the published SHA-512 integrity. To update, replace each browser distribution and its license together, verify the archive integrity, and rerun the Markdown rendering checks.

+ 202 - 0
static/vendor/dompurify.LICENSE

@@ -0,0 +1,202 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.

+ 44 - 0
static/vendor/marked.LICENSE

@@ -0,0 +1,44 @@
+# License information
+
+## Contribution License Agreement
+
+If you contribute code to this project, you are implicitly allowing your code
+to be distributed under the MIT license. You are also implicitly verifying that
+all code is your original work. `</legalese>`
+
+## Marked
+
+Copyright (c) 2018+, MarkedJS (https://github.com/markedjs/)
+Copyright (c) 2011-2018, Christopher Jeffrey (https://github.com/chjj/)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+## Markdown
+
+Copyright © 2004, John Gruber
+http://daringfireball.net/
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+* Neither the name “Markdown” nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+This software is provided by the copyright holders and contributors “as is” and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright owner or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.

Datei-Diff unterdrückt, da er zu groß ist
+ 12 - 0
static/vendor/marked.umd.js


Datei-Diff unterdrückt, da er zu groß ist
+ 4 - 0
static/vendor/purify.min.js


+ 74 - 0
tests/frontend_markdown.html

@@ -0,0 +1,74 @@
+<!doctype html>
+<html lang="zh-CN"><meta charset="utf-8"><title>Markdown regression checks</title>
+<style>body{font:14px system-ui;background:#0f1115;color:#e6e9ef;margin:24px}iframe{width:100%;height:620px;border:1px solid #2a2f3a}pre{white-space:pre-wrap}.pass{color:#34d399}.fail{color:#f87171}</style>
+<h1>Markdown regression checks</h1><pre id="result">Running…</pre><iframe title="Frontend under test" src="/static/index.html"></iframe>
+<script>
+const frame = document.querySelector('iframe');
+frame.addEventListener('load', async () => {
+  const w = frame.contentWindow;
+  const results = [];
+  const check = (condition, message) => { if (!condition) throw new Error(message); results.push('PASS ' + message); };
+  const pause = () => new Promise(resolve => setTimeout(resolve, 80));
+  const render = (source) => { const ui = w.newAssistant(); w.appendToken(ui, source); w.breakSegment(ui); return ui; };
+  const sample = '# Markdown 标题\n\n这是 **加粗**、*斜体*、~~删除线~~ 和 `inline code`。\n\n- 第一项\n  - 嵌套项\n- [x] 已完成\n\n> 引用内容\n\n| 项目 | 数值 |\n| --- | ---: |\n| 风量 | 120 |\n\n```python\ndef greet():\n    print("<hello>")\n```\n\n[文档](https://example.com)';
+  try {
+    await pause();
+    w.document.getElementById('newBtn').click();
+    const full = render(sample);
+    check(full.bubble.querySelector('h1')?.textContent === 'Markdown 标题', 'headings');
+    check(full.bubble.querySelector('strong')?.textContent === '加粗' && full.bubble.querySelector('em') && full.bubble.querySelector('del'), 'inline formatting');
+    check(full.bubble.querySelector('ul ul li') && full.bubble.querySelector('input:checked:disabled'), 'nested and task lists');
+    check(full.bubble.querySelector('blockquote') && full.bubble.querySelector('.markdown-table table tbody td'), 'quotes and GFM tables');
+    check(full.bubble.querySelector('pre code')?.textContent.includes('    print("<hello>")'), 'code indentation and literal HTML');
+    check(full.bubble.querySelector('a')?.rel === 'noopener noreferrer', 'safe external links');
+    const streamed = w.newAssistant();
+    for (const char of sample) w.appendToken(streamed, char);
+    await pause();
+    check(streamed.bubble.innerHTML === full.bubble.innerHTML, 'fragmented tokens match complete Markdown');
+    const mixed = w.newAssistant();
+    w.appendToken(mixed, '**before**');
+    const tool = w.addCardFor(mixed, 'done', '工具完成', '{"ok":true}');
+    w.appendToken(mixed, '**after**');
+    w.breakSegment(mixed);
+    await pause();
+    check(mixed.bubble.children[1] === tool && mixed.bubble.children[0].querySelector('strong').textContent === 'before' && mixed.bubble.children[2].querySelector('strong').textContent === 'after', 'tool cards preserve segment order');
+    const incomplete = render('```js\nconst value = "<tag>";');
+    check(incomplete.bubble.querySelector('pre code')?.textContent.includes('<tag>'), 'unfinished code fences during streaming');
+    const hostile = render('<img src="x" onerror="window.__xss=1"><script>window.__xss=1<\/script><svg onload="window.__xss=1"></svg><style>body{display:none}</style>[bad](javascript:alert%281%29)<a href="jav&#x61;script:alert(1)">bad</a><iframe srcdoc="bad"></iframe>');
+    check(!hostile.bubble.querySelector('script,style,svg,iframe,[onerror],[onload],a[href^="javascript:"]') && !w.__xss, 'HTML and dangerous URLs are sanitized');
+    const purifier = w.DOMPurify;
+    w.DOMPurify = undefined;
+    const fallback = render('**safe fallback** <img onerror="bad()">');
+    check(fallback.bubble.textContent.includes('**safe fallback**') && !fallback.bubble.querySelector('img'), 'missing dependency falls back to plain text');
+    w.DOMPurify = purifier;
+    const fetchOriginal = w.fetch;
+    const stub = async (url) => {
+      if (url.includes('/chat/history/')) return w.Response.json({items:[{msg_role:'assistant',content:sample}]});
+      if (url.includes('/chat/interrupt')) return new w.Response(null,{status:204});
+      if (url.includes('/sessions')) return w.Response.json({items:[]});
+      return w.Response.json({model:'test'});
+    };
+    w.fetch = stub;
+    await w.openSession({id:'markdown-history',title:'Markdown 历史消息',mode:'full'});
+    check(w.document.querySelector('#log h1')?.textContent === 'Markdown 标题' && w.document.querySelector('#log table'), 'history uses the same Markdown renderer');
+    const encode = content => new w.TextEncoder().encode('data: '+JSON.stringify({type:'token',content})+'\n\n');
+    w.fetch = async (url, options) => url === '/test-stream' ? new w.Response(new w.ReadableStream({start(c){c.enqueue(encode('## 完成时刷新\n\n**末尾**'));c.close();}})) : stub(url);
+    await w.stream('/test-stream','POST',new w.FormData());
+    check(w.document.querySelector('#log .assistant:last-child h2')?.textContent === '完成时刷新', 'stream completion flushes pending render');
+    w.fetch = async (url, options) => url === '/test-abort' ? new w.Response(new w.ReadableStream({start(c){c.enqueue(encode('**保留部分回复**')); options.signal.addEventListener('abort',()=>c.error(new w.DOMException('Stopped','AbortError')));}})) : stub(url);
+    const pending = w.stream('/test-abort','POST',new w.FormData());
+    await pause();
+    w.document.getElementById('stopBtn').click();
+    await pending;
+    check(w.document.querySelector('#log .assistant:last-child strong')?.textContent === '保留部分回复', 'stopping preserves partial Markdown');
+    w.fetch = fetchOriginal;
+    w.document.getElementById('newBtn').click();
+    render(sample);
+    document.getElementById('result').className = 'pass';
+    document.getElementById('result').textContent = results.join('\n') + '\n\n' + results.length + ' checks passed';
+  } catch (error) {
+    document.getElementById('result').className = 'fail';
+    document.getElementById('result').textContent = results.join('\n') + '\nFAIL ' + error.stack;
+  }
+});
+</script></html>

Einige Dateien werden nicht angezeigt, da zu viele Dateien in diesem Diff geändert wurden.