app.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161
  1. (function () {
  2. 'use strict';
  3. const state = {
  4. config: null,
  5. sessionId: null,
  6. messages: [],
  7. expandedMessages: new Set(),
  8. historyPage: 0,
  9. historyPageSize: 9999,
  10. historyTotal: 0,
  11. historyItems: [],
  12. model: '',
  13. outputMode: '流式输出 (Stream)',
  14. historyCount: 0,
  15. searchQuery: '',
  16. streaming: false,
  17. };
  18. const dom = {};
  19. document.addEventListener('DOMContentLoaded', init);
  20. async function init() {
  21. cacheDom();
  22. bindEvents();
  23. try {
  24. await loadConfig();
  25. const querySessionId = getSessionIdFromUrl();
  26. let loadedFromQuery = false;
  27. if (querySessionId !== null) {
  28. try {
  29. await loadSession(querySessionId, { silent: true, updateUrl: true, replaceUrl: true });
  30. loadedFromQuery = true;
  31. } catch (err) {
  32. console.warn('Failed to load session from URL parameter:', err);
  33. showToast('指定的会话不存在,已加载最新会话。', 'error');
  34. }
  35. }
  36. if (!loadedFromQuery) {
  37. await loadLatestSession({ updateUrl: true, replaceUrl: true });
  38. }
  39. await loadHistory();
  40. } catch (err) {
  41. showToast(err.message || '初始化失败', 'error');
  42. }
  43. renderSidebar();
  44. renderMessages();
  45. renderHistory();
  46. }
  47. function cacheDom() {
  48. dom.modelSelect = document.getElementById('model-select');
  49. dom.outputMode = document.getElementById('output-mode');
  50. dom.searchInput = document.getElementById('search-input');
  51. dom.searchFeedback = document.getElementById('search-feedback');
  52. dom.historyRange = document.getElementById('history-range');
  53. dom.historyRangeLabel = document.getElementById('history-range-label');
  54. dom.historyRangeValue = document.getElementById('history-range-value');
  55. dom.historyList = document.getElementById('history-list');
  56. dom.historyCount = document.getElementById('history-count');
  57. dom.historyPrev = document.getElementById('history-prev');
  58. dom.historyNext = document.getElementById('history-next');
  59. dom.newChatButton = document.getElementById('new-chat-btn');
  60. dom.chatMessages = document.getElementById('chat-messages');
  61. dom.chatForm = document.getElementById('chat-form');
  62. dom.chatInput = document.getElementById('chat-input');
  63. dom.sendButton = document.getElementById('send-btn');
  64. dom.fileInput = document.getElementById('file-input');
  65. dom.chatStatus = document.getElementById('chat-status');
  66. dom.toast = document.getElementById('toast');
  67. if (dom.sendButton && !dom.sendButton.dataset.defaultText) {
  68. dom.sendButton.dataset.defaultText = dom.sendButton.textContent || '发送';
  69. }
  70. }
  71. function bindEvents() {
  72. dom.modelSelect.addEventListener('change', () => {
  73. state.model = dom.modelSelect.value;
  74. });
  75. dom.outputMode.addEventListener('change', () => {
  76. state.outputMode = dom.outputMode.value;
  77. });
  78. dom.searchInput.addEventListener('input', () => {
  79. state.searchQuery = dom.searchInput.value.trim();
  80. state.expandedMessages = new Set();
  81. renderMessages();
  82. });
  83. dom.historyRange.addEventListener('input', () => {
  84. state.historyCount = Number(dom.historyRange.value || 0);
  85. updateHistorySlider();
  86. });
  87. dom.historyPrev.addEventListener('click', async () => {
  88. if (state.historyPage > 0) {
  89. state.historyPage -= 1;
  90. await loadHistory();
  91. }
  92. });
  93. dom.historyNext.addEventListener('click', async () => {
  94. const totalPages = Math.ceil(state.historyTotal / state.historyPageSize) || 1;
  95. if (state.historyPage < totalPages - 1) {
  96. state.historyPage += 1;
  97. await loadHistory();
  98. }
  99. });
  100. dom.newChatButton.addEventListener('click', async () => {
  101. if (state.streaming) {
  102. showToast('请等待当前回复完成后再新建会话', 'error');
  103. return;
  104. }
  105. try {
  106. const data = await fetchJSON('/api/session/new', { method: 'POST' });
  107. state.sessionId = data.session_id;
  108. state.messages = [];
  109. state.historyCount = 0;
  110. state.searchQuery = '';
  111. dom.searchInput.value = '';
  112. state.expandedMessages = new Set();
  113. state.historyPage = 0;
  114. renderSidebar();
  115. renderMessages();
  116. renderHistory();
  117. updateSessionInUrl(state.sessionId, { replace: false });
  118. showToast('当前会话已清空。', 'success');
  119. await loadHistory();
  120. } catch (err) {
  121. showToast(err.message || '新建会话失败', 'error');
  122. }
  123. });
  124. dom.chatForm.addEventListener('submit', handleSubmitMessage);
  125. dom.chatInput.addEventListener('keydown', (event) => {
  126. if (event.key === 'Enter' && !event.shiftKey && !event.ctrlKey && !event.altKey) {
  127. event.preventDefault();
  128. if (typeof dom.chatForm.requestSubmit === 'function') {
  129. dom.chatForm.requestSubmit();
  130. } else if (dom.sendButton) {
  131. dom.sendButton.click();
  132. }
  133. }
  134. });
  135. window.addEventListener('popstate', handlePopState);
  136. }
  137. async function loadConfig() {
  138. const config = await fetchJSON('/api/config');
  139. state.config = config;
  140. const models = Array.isArray(config.models) ? config.models : [];
  141. state.model = config.default_model || models[0] || '';
  142. populateSelect(dom.modelSelect, models, state.model);
  143. populateSelect(dom.outputMode, config.output_modes || [], state.outputMode);
  144. }
  145. function populateSelect(selectEl, values, selected) {
  146. selectEl.innerHTML = '';
  147. values.forEach((value) => {
  148. const option = document.createElement('option');
  149. option.value = value;
  150. option.textContent = value;
  151. if (value === selected) {
  152. option.selected = true;
  153. }
  154. selectEl.appendChild(option);
  155. });
  156. if (!values.length) {
  157. const option = document.createElement('option');
  158. option.value = '';
  159. option.textContent = '无可用选项';
  160. selectEl.appendChild(option);
  161. }
  162. }
  163. async function loadLatestSession(options = {}) {
  164. const { updateUrl = true, replaceUrl = false } = options;
  165. const data = await fetchJSON('/api/session/latest');
  166. state.sessionId = typeof data.session_id === 'number' ? data.session_id : 0;
  167. state.messages = Array.isArray(data.messages) ? data.messages : [];
  168. state.expandedMessages = new Set();
  169. state.historyCount = Math.min(state.historyCount, state.messages.length);
  170. state.searchQuery = '';
  171. dom.searchInput.value = '';
  172. state.historyPage = 0;
  173. renderSidebar();
  174. renderMessages();
  175. renderHistory();
  176. if (updateUrl) {
  177. updateSessionInUrl(state.sessionId, { replace: replaceUrl });
  178. }
  179. }
  180. async function loadSession(sessionId, options = {}) {
  181. const { silent = false, updateUrl = true, replaceUrl = false } = options;
  182. if (state.streaming) {
  183. if (!silent) {
  184. showToast('请等待当前回复完成后再切换会话', 'error');
  185. }
  186. return false;
  187. }
  188. try {
  189. const data = await fetchJSON(`/api/session/${sessionId}`);
  190. state.sessionId = data.session_id;
  191. state.messages = Array.isArray(data.messages) ? data.messages : [];
  192. state.historyCount = Math.min(state.historyCount, state.messages.length);
  193. state.expandedMessages = new Set();
  194. state.searchQuery = '';
  195. dom.searchInput.value = '';
  196. renderSidebar();
  197. renderMessages();
  198. renderHistory();
  199. if (updateUrl) {
  200. updateSessionInUrl(state.sessionId, { replace: replaceUrl });
  201. }
  202. return true;
  203. } catch (err) {
  204. if (!silent) {
  205. showToast(err.message || '加载会话失败', 'error');
  206. }
  207. throw err;
  208. }
  209. }
  210. async function loadHistory() {
  211. try {
  212. const data = await fetchJSON(`/api/history?page=${state.historyPage}&page_size=${state.historyPageSize}`);
  213. const total = data.total || 0;
  214. const items = Array.isArray(data.items) ? data.items : [];
  215. if (state.historyPage > 0 && items.length === 0 && total > 0) {
  216. const maxPage = Math.max(0, Math.ceil(total / state.historyPageSize) - 1);
  217. if (state.historyPage > maxPage) {
  218. state.historyPage = maxPage;
  219. await loadHistory();
  220. return;
  221. }
  222. }
  223. state.historyTotal = total;
  224. state.historyItems = items;
  225. renderHistory();
  226. } catch (err) {
  227. showToast(err.message || '获取历史记录失败', 'error');
  228. }
  229. }
  230. function renderSidebar() {
  231. if (state.config) {
  232. populateSelect(dom.modelSelect, state.config.models || [], state.model);
  233. populateSelect(dom.outputMode, state.config.output_modes || [], state.outputMode);
  234. }
  235. updateHistorySlider();
  236. updateSearchFeedback();
  237. }
  238. function updateHistorySlider() {
  239. const total = state.messages.length;
  240. dom.historyRange.max = String(total);
  241. state.historyCount = Math.min(state.historyCount, total);
  242. dom.historyRange.value = String(state.historyCount);
  243. dom.historyRangeLabel.textContent = `选择使用的历史消息数量(共${total}条)`;
  244. dom.historyRangeValue.textContent = `您选择的历史消息数量是: ${state.historyCount}`;
  245. }
  246. function updateSearchFeedback() {
  247. if (!state.searchQuery) {
  248. dom.searchFeedback.textContent = '无匹配。';
  249. return;
  250. }
  251. const matches = state.messages.filter((msg) => messageMatches(msg.content, state.searchQuery)).length;
  252. dom.searchFeedback.textContent = `共找到 ${matches} 条匹配。`;
  253. }
  254. function setStatus(message, stateClass) {
  255. if (!dom.chatStatus) {
  256. return;
  257. }
  258. dom.chatStatus.textContent = message || '';
  259. dom.chatStatus.classList.remove('running', 'error');
  260. if (!message) {
  261. return;
  262. }
  263. if (stateClass) {
  264. dom.chatStatus.classList.add(stateClass);
  265. }
  266. }
  267. function setStreaming(active) {
  268. state.streaming = active;
  269. if (dom.sendButton) {
  270. dom.sendButton.disabled = active;
  271. const defaultText = dom.sendButton.dataset.defaultText || '发送';
  272. dom.sendButton.textContent = active ? '发送中…' : defaultText;
  273. }
  274. if (dom.newChatButton) {
  275. dom.newChatButton.disabled = active;
  276. }
  277. if (active) {
  278. setStatus('正在生成回复…', 'running');
  279. }
  280. }
  281. function renderHistory() {
  282. if (dom.historyCount) {
  283. const total = Number.isFinite(state.historyTotal) ? state.historyTotal : 0;
  284. dom.historyCount.textContent = `共 ${total} 条`;
  285. }
  286. dom.historyList.innerHTML = '';
  287. if (!state.historyItems.length) {
  288. const empty = document.createElement('div');
  289. empty.className = 'sidebar-help';
  290. empty.textContent = '无记录。';
  291. dom.historyList.appendChild(empty);
  292. } else {
  293. state.historyItems.forEach((item) => {
  294. const row = document.createElement('div');
  295. row.className = 'history-row';
  296. row.dataset.sessionId = String(item.session_id);
  297. row.setAttribute('role', 'listitem');
  298. if (item.session_id === state.sessionId) {
  299. row.classList.add('active');
  300. }
  301. const loadLink = document.createElement('a');
  302. loadLink.className = 'history-title-link';
  303. loadLink.href = buildSessionUrl(item.session_id);
  304. const displayTitle = (item.title && item.title.trim()) ? item.title.trim() : `会话 #${item.session_id}`;
  305. const primary = document.createElement('span');
  306. primary.className = 'history-title-text';
  307. primary.textContent = displayTitle;
  308. loadLink.appendChild(primary);
  309. const subtitle = document.createElement('span');
  310. subtitle.className = 'history-subtitle';
  311. subtitle.textContent = item.filename ? item.filename : `会话 #${item.session_id}`;
  312. loadLink.appendChild(subtitle);
  313. loadLink.title = `会话 #${item.session_id} · 点击加载`;
  314. loadLink.addEventListener('click', async (event) => {
  315. const isModified = event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0;
  316. if (isModified) {
  317. return;
  318. }
  319. event.preventDefault();
  320. try {
  321. await loadSession(item.session_id, { replaceUrl: false });
  322. } catch (err) {
  323. console.warn('Failed to load session from history list:', err);
  324. }
  325. });
  326. row.appendChild(loadLink);
  327. const moveButton = document.createElement('button');
  328. moveButton.className = 'history-icon-button';
  329. moveButton.type = 'button';
  330. moveButton.textContent = '📦';
  331. moveButton.title = '移动到备份文件夹';
  332. moveButton.addEventListener('click', async (event) => {
  333. event.stopPropagation();
  334. try {
  335. await fetchJSON('/api/history/move', {
  336. method: 'POST',
  337. body: { session_id: item.session_id },
  338. });
  339. showToast('已移动到备份。', 'success');
  340. await loadHistory();
  341. } catch (err) {
  342. showToast(err.message || '移动失败', 'error');
  343. }
  344. });
  345. row.appendChild(moveButton);
  346. const deleteButton = document.createElement('button');
  347. deleteButton.className = 'history-icon-button';
  348. deleteButton.type = 'button';
  349. deleteButton.textContent = '❌';
  350. deleteButton.title = '删除';
  351. deleteButton.addEventListener('click', async (event) => {
  352. event.stopPropagation();
  353. try {
  354. await fetchJSON(`/api/history/${item.session_id}`, { method: 'DELETE' });
  355. showToast('已删除。', 'success');
  356. if (item.session_id === state.sessionId) {
  357. await loadLatestSession();
  358. }
  359. await loadHistory();
  360. } catch (err) {
  361. showToast(err.message || '删除失败', 'error');
  362. }
  363. });
  364. row.appendChild(deleteButton);
  365. dom.historyList.appendChild(row);
  366. });
  367. }
  368. const totalPages = Math.ceil(state.historyTotal / state.historyPageSize) || 1;
  369. dom.historyPrev.disabled = state.historyPage <= 0;
  370. dom.historyNext.disabled = state.historyPage >= totalPages - 1;
  371. }
  372. function renderMessages() {
  373. dom.chatMessages.innerHTML = '';
  374. const total = state.messages.length;
  375. const searching = Boolean(state.searchQuery);
  376. state.messages.forEach((message, index) => {
  377. const wrapper = document.createElement('div');
  378. wrapper.className = `message ${message.role === 'assistant' ? 'assistant' : 'user'}`;
  379. wrapper.dataset.index = String(index);
  380. const header = document.createElement('div');
  381. header.className = 'message-header';
  382. header.textContent = message.role === 'assistant' ? 'Assistant' : 'User';
  383. wrapper.appendChild(header);
  384. const contentEl = document.createElement('div');
  385. contentEl.className = 'message-content';
  386. const expanded = state.expandedMessages.has(index);
  387. const shouldClamp = !searching && index < total - 1 && !expanded;
  388. if (shouldClamp) {
  389. contentEl.classList.add('clamped');
  390. }
  391. const query = state.searchQuery && messageMatches(message.content, state.searchQuery)
  392. ? state.searchQuery
  393. : '';
  394. renderContent(message.content, contentEl, query);
  395. wrapper.appendChild(contentEl);
  396. const actions = document.createElement('div');
  397. actions.className = 'message-actions';
  398. if (!searching && index < total - 1) {
  399. const toggleButton = document.createElement('button');
  400. toggleButton.className = 'message-button';
  401. toggleButton.textContent = expanded ? '<<' : '>>';
  402. toggleButton.addEventListener('click', () => {
  403. if (expanded) {
  404. state.expandedMessages.delete(index);
  405. } else {
  406. state.expandedMessages.add(index);
  407. }
  408. renderMessages();
  409. });
  410. actions.appendChild(toggleButton);
  411. }
  412. if (message.role === 'assistant') {
  413. const exportButton = document.createElement('button');
  414. exportButton.className = 'message-button';
  415. exportButton.textContent = '导出';
  416. exportButton.addEventListener('click', async () => {
  417. try {
  418. await fetchJSON('/api/export', {
  419. method: 'POST',
  420. body: { content: message.content },
  421. });
  422. showToast('已导出到 blog 文件夹。', 'success');
  423. } catch (err) {
  424. showToast(err.message || '导出失败', 'error');
  425. }
  426. });
  427. actions.appendChild(exportButton);
  428. }
  429. wrapper.appendChild(actions);
  430. dom.chatMessages.appendChild(wrapper);
  431. });
  432. updateSearchFeedback();
  433. scrollToBottom();
  434. }
  435. function renderContent(content, container, query) {
  436. container.innerHTML = '';
  437. const highlightQuery = query || '';
  438. if (typeof content === 'string' || content === null || content === undefined) {
  439. renderMarkdownContent(container, String(content || ''));
  440. applyHighlight(container, highlightQuery);
  441. return;
  442. }
  443. if (Array.isArray(content)) {
  444. content.forEach((part) => {
  445. if (part && part.type === 'text') {
  446. const textContainer = document.createElement('div');
  447. renderMarkdownContent(textContainer, String(part.text || ''));
  448. container.appendChild(textContainer);
  449. } else if (part && part.type === 'image_url') {
  450. const url = part.image_url && part.image_url.url ? part.image_url.url : '';
  451. const img = document.createElement('img');
  452. img.src = url;
  453. img.alt = '上传的图片';
  454. img.loading = 'lazy';
  455. container.appendChild(img);
  456. } else {
  457. const fallback = document.createElement('pre');
  458. fallback.textContent = JSON.stringify(part, null, 2);
  459. container.appendChild(fallback);
  460. }
  461. });
  462. applyHighlight(container, highlightQuery);
  463. return;
  464. }
  465. const pre = document.createElement('pre');
  466. pre.textContent = typeof content === 'object' ? JSON.stringify(content, null, 2) : String(content || '');
  467. container.appendChild(pre);
  468. applyHighlight(container, highlightQuery);
  469. }
  470. function renderMarkdownContent(container, text) {
  471. const normalized = String(text || '').replace(/\r\n/g, '\n');
  472. const lines = normalized.split('\n');
  473. let paragraphBuffer = [];
  474. let listBuffer = [];
  475. let blockquoteBuffer = [];
  476. let inCodeBlock = false;
  477. let codeLang = '';
  478. let codeBuffer = [];
  479. const flushParagraph = () => {
  480. if (!paragraphBuffer.length) {
  481. return;
  482. }
  483. const paragraphText = paragraphBuffer.join('\n');
  484. const paragraph = document.createElement('p');
  485. appendInlineMarkdown(paragraph, paragraphText);
  486. container.appendChild(paragraph);
  487. paragraphBuffer = [];
  488. };
  489. const flushList = () => {
  490. if (!listBuffer.length) {
  491. return;
  492. }
  493. const list = document.createElement('ul');
  494. listBuffer.forEach((item) => {
  495. const li = document.createElement('li');
  496. appendInlineMarkdown(li, item);
  497. list.appendChild(li);
  498. });
  499. container.appendChild(list);
  500. listBuffer = [];
  501. };
  502. const flushBlockquote = () => {
  503. if (!blockquoteBuffer.length) {
  504. return;
  505. }
  506. const blockquote = document.createElement('blockquote');
  507. const textContent = blockquoteBuffer.join('\n');
  508. appendInlineMarkdown(blockquote, textContent);
  509. container.appendChild(blockquote);
  510. blockquoteBuffer = [];
  511. };
  512. const flushCode = () => {
  513. const pre = document.createElement('pre');
  514. const code = document.createElement('code');
  515. if (codeLang) {
  516. code.dataset.lang = codeLang;
  517. code.className = `language-${codeLang}`;
  518. }
  519. code.textContent = codeBuffer.join('\n');
  520. pre.appendChild(code);
  521. container.appendChild(pre);
  522. codeBuffer = [];
  523. codeLang = '';
  524. inCodeBlock = false;
  525. };
  526. lines.forEach((rawLine) => {
  527. const line = rawLine;
  528. const fenceMatch = line.match(/^```([A-Za-z0-9_-]+)?\s*$/);
  529. if (fenceMatch) {
  530. if (inCodeBlock) {
  531. flushCode();
  532. } else {
  533. flushParagraph();
  534. flushList();
  535. flushBlockquote();
  536. inCodeBlock = true;
  537. codeLang = fenceMatch[1] ? fenceMatch[1].toLowerCase() : '';
  538. codeBuffer = [];
  539. }
  540. return;
  541. }
  542. if (inCodeBlock) {
  543. codeBuffer.push(line);
  544. return;
  545. }
  546. const listMatch = line.match(/^\s*[-*+]\s+(.*)$/);
  547. if (listMatch) {
  548. flushParagraph();
  549. flushBlockquote();
  550. listBuffer.push(listMatch[1]);
  551. return;
  552. }
  553. const blockquoteMatch = line.match(/^>\s?(.*)$/);
  554. if (blockquoteMatch) {
  555. flushParagraph();
  556. flushList();
  557. blockquoteBuffer.push(blockquoteMatch[1]);
  558. return;
  559. }
  560. if (!line.trim()) {
  561. flushParagraph();
  562. flushList();
  563. flushBlockquote();
  564. return;
  565. }
  566. const headingMatch = line.match(/^(#{1,6})\s+(.*)$/);
  567. if (headingMatch) {
  568. flushParagraph();
  569. flushList();
  570. flushBlockquote();
  571. const level = Math.min(headingMatch[1].length, 6);
  572. const heading = document.createElement(`h${level}`);
  573. appendInlineMarkdown(heading, headingMatch[2]);
  574. container.appendChild(heading);
  575. return;
  576. }
  577. paragraphBuffer.push(line);
  578. });
  579. if (inCodeBlock) {
  580. flushCode();
  581. }
  582. flushParagraph();
  583. flushList();
  584. flushBlockquote();
  585. }
  586. function appendInlineMarkdown(parent, text) {
  587. const pattern = /(!?\[[^\]]*\]\([^\)]+\)|`[^`]*`|\*\*[^*]+\*\*|\*[^*]+\*|~~[^~]+~~)/g;
  588. let lastIndex = 0;
  589. let match;
  590. while ((match = pattern.exec(text)) !== null) {
  591. if (match.index > lastIndex) {
  592. appendTextNode(parent, text.slice(lastIndex, match.index));
  593. }
  594. appendMarkdownToken(parent, match[0]);
  595. lastIndex = pattern.lastIndex;
  596. }
  597. if (lastIndex < text.length) {
  598. appendTextNode(parent, text.slice(lastIndex));
  599. }
  600. }
  601. function appendMarkdownToken(parent, token) {
  602. if (token.startsWith('`') && token.endsWith('`')) {
  603. const code = document.createElement('code');
  604. code.textContent = token.slice(1, -1);
  605. parent.appendChild(code);
  606. return;
  607. }
  608. if (token.startsWith('**') && token.endsWith('**')) {
  609. const strong = document.createElement('strong');
  610. appendInlineMarkdown(strong, token.slice(2, -2));
  611. parent.appendChild(strong);
  612. return;
  613. }
  614. if (token.startsWith('*') && token.endsWith('*')) {
  615. const em = document.createElement('em');
  616. appendInlineMarkdown(em, token.slice(1, -1));
  617. parent.appendChild(em);
  618. return;
  619. }
  620. if (token.startsWith('~~') && token.endsWith('~~')) {
  621. const del = document.createElement('del');
  622. appendInlineMarkdown(del, token.slice(2, -2));
  623. parent.appendChild(del);
  624. return;
  625. }
  626. if (token.startsWith('![')) {
  627. const match = token.match(/^!\[([^\]]*)\]\(([^\)]+)\)$/);
  628. if (match) {
  629. const img = document.createElement('img');
  630. img.alt = match[1];
  631. img.src = match[2];
  632. img.loading = 'lazy';
  633. parent.appendChild(img);
  634. return;
  635. }
  636. }
  637. if (token.startsWith('[')) {
  638. const match = token.match(/^\[([^\]]+)\]\(([^\)]+)\)$/);
  639. if (match) {
  640. const anchor = document.createElement('a');
  641. anchor.href = match[2];
  642. anchor.target = '_blank';
  643. anchor.rel = 'noopener noreferrer';
  644. anchor.textContent = match[1];
  645. parent.appendChild(anchor);
  646. return;
  647. }
  648. }
  649. appendTextNode(parent, token);
  650. }
  651. function appendTextNode(parent, text) {
  652. if (!text) {
  653. return;
  654. }
  655. const fragments = String(text).split(/(\n)/);
  656. fragments.forEach((fragment) => {
  657. if (fragment === '\n') {
  658. parent.appendChild(document.createElement('br'));
  659. } else if (fragment) {
  660. parent.appendChild(document.createTextNode(fragment));
  661. }
  662. });
  663. }
  664. function clearHighlights(root) {
  665. if (!root) {
  666. return;
  667. }
  668. root.querySelectorAll('mark.hl').forEach((mark) => {
  669. const parent = mark.parentNode;
  670. if (!parent) {
  671. return;
  672. }
  673. while (mark.firstChild) {
  674. parent.insertBefore(mark.firstChild, mark);
  675. }
  676. parent.removeChild(mark);
  677. parent.normalize();
  678. });
  679. }
  680. function applyHighlight(root, query) {
  681. if (!root) {
  682. return;
  683. }
  684. clearHighlights(root);
  685. if (!query) {
  686. return;
  687. }
  688. const lowerQuery = query.toLowerCase();
  689. const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null);
  690. const matches = [];
  691. while (walker.nextNode()) {
  692. const node = walker.currentNode;
  693. if (!node || !node.nodeValue || !node.nodeValue.trim()) {
  694. continue;
  695. }
  696. const text = node.nodeValue;
  697. const lowerText = text.toLowerCase();
  698. let index = lowerText.indexOf(lowerQuery);
  699. while (index !== -1) {
  700. matches.push({ node, start: index, end: index + query.length });
  701. index = lowerText.indexOf(lowerQuery, index + query.length);
  702. }
  703. }
  704. for (let i = matches.length - 1; i >= 0; i -= 1) {
  705. const { node, start, end } = matches[i];
  706. if (!node || !node.parentNode) {
  707. continue;
  708. }
  709. const range = document.createRange();
  710. range.setStart(node, start);
  711. range.setEnd(node, end);
  712. const mark = document.createElement('mark');
  713. mark.className = 'hl';
  714. range.surroundContents(mark);
  715. }
  716. }
  717. function messageMatches(content, query) {
  718. if (!query) {
  719. return false;
  720. }
  721. const lower = query.toLowerCase();
  722. if (typeof content === 'string') {
  723. return content.toLowerCase().includes(lower);
  724. }
  725. if (Array.isArray(content)) {
  726. return content.some((part) => {
  727. if (!part || part.type !== 'text') {
  728. return false;
  729. }
  730. return String(part.text || '').toLowerCase().includes(lower);
  731. });
  732. }
  733. try {
  734. return JSON.stringify(content).toLowerCase().includes(lower);
  735. } catch (err) {
  736. return false;
  737. }
  738. }
  739. async function handleSubmitMessage(event) {
  740. event.preventDefault();
  741. if (state.streaming) {
  742. showToast('请等待当前回复完成', 'error');
  743. return;
  744. }
  745. const text = dom.chatInput.value.trim();
  746. const files = dom.fileInput.files;
  747. if (!text && (!files || files.length === 0)) {
  748. showToast('请输入内容或上传文件', 'error');
  749. return;
  750. }
  751. let uploads = [];
  752. const hasFiles = files && files.length > 0;
  753. if (hasFiles) {
  754. try {
  755. setStatus('正在上传文件…', 'running');
  756. uploads = await uploadAttachments(files);
  757. } catch (err) {
  758. const message = err.message || '文件上传失败';
  759. setStatus(message, 'error');
  760. showToast(message, 'error');
  761. return;
  762. }
  763. }
  764. const { content } = buildUserContent(text, uploads);
  765. if (!hasContent(content)) {
  766. setStatus('内容不能为空', 'error');
  767. showToast('内容不能为空', 'error');
  768. return;
  769. }
  770. setStatus('');
  771. state.expandedMessages = new Set();
  772. const userMessage = { role: 'user', content };
  773. state.messages.push(userMessage);
  774. renderMessages();
  775. scrollToBottom();
  776. dom.chatInput.value = '';
  777. dom.fileInput.value = '';
  778. const assistantMessage = { role: 'assistant', content: '' };
  779. state.messages.push(assistantMessage);
  780. const assistantIndex = state.messages.length - 1;
  781. renderMessages();
  782. scrollToBottom();
  783. const payload = {
  784. session_id: state.sessionId ?? 0,
  785. model: state.model,
  786. content,
  787. history_count: state.historyCount,
  788. stream: state.outputMode === '流式输出 (Stream)',
  789. };
  790. setStreaming(true);
  791. try {
  792. if (payload.stream) {
  793. await streamAssistantReply(payload, assistantMessage, assistantIndex);
  794. } else {
  795. const data = await fetchJSON('/api/chat', {
  796. method: 'POST',
  797. body: payload,
  798. });
  799. assistantMessage.content = data.message || '';
  800. updateMessageContent(assistantIndex, assistantMessage.content);
  801. showToast('已生成回复', 'success');
  802. setStatus('');
  803. }
  804. } catch (err) {
  805. state.messages.splice(assistantIndex, 1);
  806. renderMessages();
  807. const message = err.message || '发送失败';
  808. setStatus(message, 'error');
  809. showToast(message, 'error');
  810. } finally {
  811. try {
  812. state.historyPage = 0;
  813. await loadHistory();
  814. } catch (historyErr) {
  815. console.error('刷新历史记录失败', historyErr);
  816. } finally {
  817. updateHistorySlider();
  818. setStreaming(false);
  819. }
  820. }
  821. }
  822. function hasContent(content) {
  823. if (typeof content === 'string') {
  824. return Boolean(content.trim());
  825. }
  826. if (Array.isArray(content)) {
  827. return content.length > 1 || (content[0] && String(content[0].text || '').trim());
  828. }
  829. return Boolean(content);
  830. }
  831. async function uploadAttachments(fileList) {
  832. if (!fileList || fileList.length === 0) {
  833. return [];
  834. }
  835. const formData = new FormData();
  836. Array.from(fileList).forEach((file) => formData.append('files', file));
  837. const response = await fetch('/api/upload', {
  838. method: 'POST',
  839. body: formData,
  840. });
  841. if (!response.ok) {
  842. throw new Error('文件上传失败');
  843. }
  844. return await response.json();
  845. }
  846. function buildUserContent(text, uploads) {
  847. const results = Array.isArray(uploads) ? uploads : [];
  848. if (!results.length) {
  849. return { content: text };
  850. }
  851. const contentParts = [{ type: 'text', text: text }];
  852. let additionalPrompt = '';
  853. results.forEach((item) => {
  854. if (item.type === 'image' && item.data) {
  855. contentParts.push({
  856. type: 'image_url',
  857. image_url: { url: item.data },
  858. });
  859. } else if (item.type === 'file' && item.url) {
  860. additionalPrompt += `本次提问包含:${item.url} 文件\n`;
  861. }
  862. });
  863. const promptSuffix = additionalPrompt.trim();
  864. if (contentParts.length > 1) {
  865. const base = contentParts[0].text || '';
  866. contentParts[0].text = promptSuffix ? `${base}\n${promptSuffix}`.trim() : base;
  867. return { content: contentParts };
  868. }
  869. let combined = text || '';
  870. if (promptSuffix) {
  871. combined = combined ? `${combined}\n${promptSuffix}` : promptSuffix;
  872. }
  873. return { content: combined.trim() };
  874. }
  875. async function streamAssistantReply(payload, assistantMessage, assistantIndex) {
  876. const response = await fetch('/api/chat', {
  877. method: 'POST',
  878. headers: { 'Content-Type': 'application/json' },
  879. body: JSON.stringify(payload),
  880. });
  881. if (!response.ok || !response.body) {
  882. const errorText = await safeReadText(response);
  883. throw new Error(errorText || '生成失败');
  884. }
  885. const reader = response.body.getReader();
  886. const decoder = new TextDecoder('utf-8');
  887. let buffer = '';
  888. let done = false;
  889. while (!done) {
  890. const { value, done: streamDone } = await reader.read();
  891. done = streamDone;
  892. if (value) {
  893. buffer += decoder.decode(value, { stream: !done });
  894. let newlineIndex = buffer.indexOf('\n');
  895. while (newlineIndex !== -1) {
  896. const line = buffer.slice(0, newlineIndex).trim();
  897. buffer = buffer.slice(newlineIndex + 1);
  898. if (line) {
  899. const status = handleStreamLine(line, assistantMessage, assistantIndex);
  900. if (status === 'end') {
  901. return;
  902. }
  903. }
  904. newlineIndex = buffer.indexOf('\n');
  905. }
  906. }
  907. }
  908. setStatus('');
  909. }
  910. function handleStreamLine(line, assistantMessage, assistantIndex) {
  911. let payload;
  912. try {
  913. payload = JSON.parse(line);
  914. } catch (err) {
  915. return;
  916. }
  917. if (payload.type === 'delta') {
  918. if (typeof assistantMessage.content !== 'string') {
  919. assistantMessage.content = '';
  920. }
  921. assistantMessage.content += payload.text || '';
  922. updateMessageContent(assistantIndex, assistantMessage.content);
  923. scrollToBottom();
  924. return null;
  925. } else if (payload.type === 'end') {
  926. showToast('已生成回复', 'success');
  927. setStatus('');
  928. return 'end';
  929. } else if (payload.type === 'error') {
  930. throw new Error(payload.message || '生成失败');
  931. }
  932. }
  933. function updateMessageContent(index, content) {
  934. const selector = `.message[data-index="${index}"] .message-content`;
  935. const node = dom.chatMessages.querySelector(selector);
  936. if (!node) {
  937. renderMessages();
  938. return;
  939. }
  940. node.classList.remove('clamped');
  941. renderContent(content, node, state.searchQuery && messageMatches(content, state.searchQuery) ? state.searchQuery : '');
  942. }
  943. function scrollToBottom() {
  944. dom.chatMessages.scrollTop = dom.chatMessages.scrollHeight;
  945. }
  946. function getSessionIdFromUrl() {
  947. const params = new URLSearchParams(window.location.search);
  948. const value = params.get('session');
  949. if (!value) {
  950. return null;
  951. }
  952. const parsed = Number(value);
  953. return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
  954. }
  955. function buildSessionUrl(sessionId) {
  956. const current = new URL(window.location.href);
  957. if (Number.isInteger(sessionId) && sessionId >= 0) {
  958. current.searchParams.set('session', String(sessionId));
  959. } else {
  960. current.searchParams.delete('session');
  961. }
  962. current.hash = '';
  963. const search = current.searchParams.toString();
  964. return `${current.pathname}${search ? `?${search}` : ''}`;
  965. }
  966. function updateSessionInUrl(sessionId, options = {}) {
  967. if (!window.history || typeof window.history.replaceState !== 'function') {
  968. return;
  969. }
  970. const { replace = false } = options;
  971. const target = buildSessionUrl(sessionId);
  972. const stateData = { sessionId };
  973. if (replace) {
  974. window.history.replaceState(stateData, '', target);
  975. } else {
  976. window.history.pushState(stateData, '', target);
  977. }
  978. }
  979. async function handlePopState(event) {
  980. if (state.streaming) {
  981. return;
  982. }
  983. const stateSessionId = event.state && Number.isInteger(event.state.sessionId)
  984. ? event.state.sessionId
  985. : getSessionIdFromUrl();
  986. try {
  987. if (stateSessionId !== null) {
  988. await loadSession(stateSessionId, { silent: true, updateUrl: false });
  989. } else {
  990. await loadLatestSession({ updateUrl: false });
  991. }
  992. await loadHistory();
  993. } catch (err) {
  994. console.warn('Failed to restore session from history navigation:', err);
  995. }
  996. }
  997. async function fetchJSON(url, options = {}) {
  998. const opts = { ...options };
  999. opts.headers = { ...(opts.headers || {}) };
  1000. if (opts.body && !(opts.body instanceof FormData) && typeof opts.body !== 'string') {
  1001. opts.headers['Content-Type'] = 'application/json';
  1002. opts.body = JSON.stringify(opts.body);
  1003. }
  1004. const response = await fetch(url, opts);
  1005. if (!response.ok) {
  1006. const message = await readErrorMessage(response);
  1007. throw new Error(message || '请求失败');
  1008. }
  1009. if (response.status === 204) {
  1010. return {};
  1011. }
  1012. const text = await response.text();
  1013. return text ? JSON.parse(text) : {};
  1014. }
  1015. async function readErrorMessage(response) {
  1016. const text = await safeReadText(response);
  1017. if (!text) {
  1018. return response.statusText;
  1019. }
  1020. try {
  1021. const data = JSON.parse(text);
  1022. return data.detail || data.message || text;
  1023. } catch (err) {
  1024. return text;
  1025. }
  1026. }
  1027. async function safeReadText(response) {
  1028. try {
  1029. return await response.text();
  1030. } catch (err) {
  1031. return '';
  1032. }
  1033. }
  1034. let toastTimer;
  1035. function showToast(message, type = 'success') {
  1036. if (!dom.toast) {
  1037. return;
  1038. }
  1039. dom.toast.textContent = message;
  1040. dom.toast.classList.remove('hidden', 'success', 'error', 'show');
  1041. dom.toast.classList.add(type, 'show');
  1042. clearTimeout(toastTimer);
  1043. toastTimer = setTimeout(() => {
  1044. dom.toast.classList.remove('show');
  1045. toastTimer = setTimeout(() => dom.toast.classList.add('hidden'), 300);
  1046. }, 2500);
  1047. }
  1048. })();