From 59658bd326ef63327f789ec496cce9632cb339d4 Mon Sep 17 00:00:00 2001
From: wizardchen
Date: Mon, 9 Mar 2026 20:27:24 +0800
Subject: [PATCH 01/63] feat: enhance storage engine configuration and user
notifications
- Updated the summary length requirement for document summarization to 100-300 words.
- Added new localization strings for missing storage engine notifications in English, Korean, Russian, and Chinese.
- Implemented UI warnings for users regarding storage engine configuration when files exist, including confirmation dialogs for storage engine changes.
- Enhanced backend validation to ensure a storage engine is configured before allowing content uploads.
These changes improve user experience by providing clearer guidance on storage engine requirements and enhancing the overall functionality of the knowledge base management system.
---
config/config.yaml | 2 +-
frontend/src/i18n/locales/en-US.ts | 7 ++-
frontend/src/i18n/locales/ko-KR.ts | 6 +++
frontend/src/i18n/locales/ru-RU.ts | 7 ++-
frontend/src/i18n/locales/zh-CN.ts | 6 +++
.../src/views/knowledge/KnowledgeBase.vue | 49 +++++++++++++++++++
.../knowledge/KnowledgeBaseEditorModal.vue | 33 ++++++++++++-
.../knowledge/settings/KBStorageSettings.vue | 7 ++-
internal/application/service/knowledge.go | 32 ++++++++++++
internal/handler/initialization.go | 4 +-
10 files changed, 144 insertions(+), 9 deletions(-)
diff --git a/config/config.yaml b/config/config.yaml
index 299269c1..d04b9e86 100644
--- a/config/config.yaml
+++ b/config/config.yaml
@@ -141,7 +141,7 @@ conversation:
You are a precise document summarization expert. Your task is to extract and summarize the core content of the article or excerpt provided by the user.
## Core Requirements
- - Summary length should be 50-100 words, adjusted flexibly based on content complexity
+ - Summary length should be 100-300 words, adjusted flexibly based on content complexity
- Generate the summary entirely based on the provided content, without adding any information not present in the article
- Ensure the summary captures key information points and main conclusions
- Even for complex or specialized content, you must attempt to extract core points for summarization
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 8ce2b4c7..e0af4b85 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -151,6 +151,9 @@ export default {
confirmDeleteQuestion: 'Are you sure you want to delete this question? The corresponding vector index will also be removed.',
legacyQuestionCannotDelete: 'Legacy format questions cannot be deleted. Please regenerate questions.',
notInitialized: 'Knowledge base is not initialized. Please configure models in settings before uploading files',
+ missingStorageEngine: 'This knowledge base has no storage engine selected. Please configure a storage engine in settings before uploading content.',
+ missingStorageEngineUpload: 'Please configure a storage engine before uploading content',
+ goToStorageSettings: 'Go to Settings',
getInfoFailed: 'Failed to get knowledge base information, file upload is not possible',
missingId: 'Knowledge base ID is missing',
deleteFailed: 'Delete failed. Please try again later!',
@@ -1442,7 +1445,8 @@ export default {
missingId: 'Knowledge base ID is missing',
buildDataFailed: 'Failed to construct submission data',
updateSuccess: 'Configuration saved successfully',
- indexModeRequired: 'Please select an indexing mode for FAQ knowledge bases'
+ indexModeRequired: 'Please select an indexing mode for FAQ knowledge bases',
+ storageChangeConfirm: 'This knowledge base already has files. Changing the storage engine may make old files inaccessible. Do you want to proceed?'
},
document: {
title: 'Document Management',
@@ -3039,6 +3043,7 @@ export default {
notConfigured: 'Not Configured',
unavailable: 'Unavailable',
lockedHint: 'This knowledge base already has files. Cannot switch storage engine. To change, please clear all files first.',
+ changeWarning: 'Changing the storage engine only affects newly uploaded files. Existing files will still be read from the original storage engine, but some old files may become inaccessible if their paths cannot be automatically recognized.',
goGlobalSettings: 'Go to Global Settings',
engineLocal: 'Local Storage',
engineLocalDesc: 'For single-node deployment, simple and lightweight',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index d1948dfa..15b206f4 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -160,6 +160,10 @@ export default {
docActionUnsupported: "현재 지식베이스 유형은 이 작업을 지원하지 않습니다",
notInitialized:
"이 지식베이스는 아직 초기화되지 않았습니다. 설정 페이지에서 모델 정보를 먼저 구성한 후 파일을 업로드하세요",
+ missingStorageEngine:
+ "이 지식베이스에 스토리지 엔진이 선택되지 않았습니다. 콘텐츠를 업로드하기 전에 설정 페이지에서 스토리지 엔진을 구성하세요.",
+ missingStorageEngineUpload: "콘텐츠를 업로드하기 전에 스토리지 엔진을 구성하세요",
+ goToStorageSettings: "설정으로 이동",
getInfoFailed: "지식베이스 정보를 가져오는 데 실패하여 파일을 업로드할 수 없습니다",
missingId: "지식베이스 ID가 없습니다",
deleteFailed: "삭제 실패, 나중에 다시 시도하세요!",
@@ -1928,6 +1932,7 @@ export default {
buildDataFailed: "데이터 구축 실패",
updateSuccess: "설정 저장 성공",
indexModeRequired: "FAQ 인덱스 방식을 선택해주세요",
+ storageChangeConfirm: "지식베이스에 파일이 있습니다. 스토리지 엔진을 변경하면 이전 파일에 접근할 수 없게 될 수 있습니다. 계속하시겠습니까?",
},
document: {
title: "문서",
@@ -3107,6 +3112,7 @@ export default {
notConfigured: '미구성',
unavailable: '사용 불가',
lockedHint: '지식베이스에 파일이 있어 스토리지 엔진을 변경할 수 없습니다. 변경하려면 모든 파일을 먼저 삭제하세요.',
+ changeWarning: '스토리지 엔진을 변경하면 새로 업로드된 파일에만 영향을 미칩니다. 기존 파일은 여전히 원래 스토리지 엔진에서 읽히지만, 일부 이전 파일의 경로를 자동으로 인식할 수 없어 접근이 불가능할 수 있습니다.',
goGlobalSettings: '전역 설정으로 이동',
engineLocal: 'Local(로컬 스토리지)',
engineLocalDesc: '단일 노드 배포에 적합, 간단하고 가벼움',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 0ac82bf8..0faa49e0 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -129,6 +129,9 @@ export default {
confirmDeleteQuestion: 'Вы уверены, что хотите удалить этот вопрос? Соответствующий векторный индекс также будет удален.',
legacyQuestionCannotDelete: 'Вопросы в устаревшем формате нельзя удалить. Пожалуйста, сгенерируйте вопросы заново.',
notInitialized: 'База знаний не инициализирована. Пожалуйста, настройте модели в разделе настроек перед загрузкой файлов',
+ missingStorageEngine: 'Для этой базы знаний не выбрано хранилище. Пожалуйста, настройте хранилище в параметрах перед загрузкой содержимого.',
+ missingStorageEngineUpload: 'Пожалуйста, настройте хранилище перед загрузкой содержимого',
+ goToStorageSettings: 'Перейти к настройкам',
getInfoFailed: 'Не удалось получить информацию о базе знаний, загрузка файла невозможна',
missingId: 'Отсутствует ID базы знаний',
deleteFailed: 'Не удалось удалить. Пожалуйста, попробуйте позже!',
@@ -1607,7 +1610,8 @@ export default {
missingId: 'Отсутствует ID базы знаний',
buildDataFailed: 'Не удалось сформировать данные для отправки',
updateSuccess: 'Настройки сохранены',
- indexModeRequired: 'Выберите режим индексации для FAQ базы знаний'
+ indexModeRequired: 'Выберите режим индексации для FAQ базы знаний',
+ storageChangeConfirm: 'В базе знаний уже есть файлы. Смена хранилища может сделать старые файлы недоступными. Продолжить?'
},
document: {
title: 'Управление документами',
@@ -2638,6 +2642,7 @@ export default {
notConfigured: 'Не настроено',
unavailable: 'Недоступно',
lockedHint: 'В базе знаний уже есть файлы. Невозможно сменить хранилище. Для смены сначала удалите все файлы.',
+ changeWarning: 'Смена хранилища влияет только на новые загружаемые файлы. Существующие файлы по-прежнему будут читаться из прежнего хранилища, но некоторые старые файлы могут стать недоступными.',
goGlobalSettings: 'Перейти в глобальные настройки',
engineLocal: 'Локальное хранилище',
engineLocalDesc: 'Для однонодового развёртывания, простое и лёгкое',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index a084635e..128d0f0f 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -152,6 +152,10 @@ export default {
docActionUnsupported: "当前知识库类型不支持该操作",
notInitialized:
"该知识库尚未完成初始化配置,请先前往设置页面配置模型信息后再上传文件",
+ missingStorageEngine:
+ "该知识库尚未选择存储引擎,请先前往设置页面配置存储引擎后再上传内容。",
+ missingStorageEngineUpload: "请先配置存储引擎后再上传内容",
+ goToStorageSettings: "前往配置",
getInfoFailed: "获取知识库信息失败,无法上传文件",
missingId: "缺少知识库ID",
deleteFailed: "删除失败,请稍后再试!",
@@ -1897,6 +1901,7 @@ export default {
buildDataFailed: "数据构建失败",
updateSuccess: "配置保存成功",
indexModeRequired: "请选择 FAQ 的索引方式",
+ storageChangeConfirm: "知识库中已有文件,更改存储引擎后旧文件可能无法正常访问。是否确认更改?",
},
document: {
title: "文档",
@@ -3036,6 +3041,7 @@ export default {
notConfigured: "未配置",
unavailable: "不可用",
lockedHint: "知识库中已有文件,无法切换存储引擎。如需更换,请先清空知识库中的所有文件。",
+ changeWarning: "更改存储引擎仅影响新上传的文件。已有文件仍使用原存储引擎读取,但部分旧文件可能无法自动识别而导致访问失败。",
goGlobalSettings: "去全局设置中配置",
engineLocal: "Local(本地存储)",
engineLocalDesc: "仅适合单机部署,简单轻量",
diff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vue
index 494365fc..548bced0 100644
--- a/frontend/src/views/knowledge/KnowledgeBase.vue
+++ b/frontend/src/views/knowledge/KnowledgeBase.vue
@@ -43,6 +43,11 @@ const folderUploadInputRef = ref(null);
const uploading = ref(false);
const kbLoading = ref(false);
const isFAQ = computed(() => (kbInfo.value?.type || '') === 'faq');
+const missingStorageEngine = computed(() => {
+ if (!kbInfo.value || isFAQ.value) return false
+ const spc = kbInfo.value.storage_provider_config
+ return !spc || !spc.provider
+})
const parserEngines = ref([]);
const supportedFileTypes = computed>(() => {
@@ -947,6 +952,10 @@ const ensureDocumentKbReady = () => {
MessagePlugin.warning(t('knowledgeBase.notInitialized'));
return false;
}
+ if (missingStorageEngine.value) {
+ MessagePlugin.warning(t('knowledgeBase.missingStorageEngineUpload'));
+ return false;
+ }
return true;
};
@@ -1459,6 +1468,11 @@ async function createNewSession(value: string): Promise {
{{ $t('knowledgeBase.unsupportedTypesHint', { types: unsupportedFileTypes.map(t => '.' + t).join('、') }) }}{{ $t('knowledgeBase.goToParserSettings') }} →
';
+ });
+ html = html.replace(/`([^`]+)`/g, '$1');
+ html = html.replace(/((?:\|.+\|\n)+)/g, function (tableBlock) {
+ var rows = tableBlock.trim().split('\n');
+ if (rows.length < 2) return tableBlock;
+ var out = '
';
+ rows.forEach(function (row, i) {
+ if (/^\|[\s\-:|]+\|$/.test(row)) return;
+ var tag = i === 0 ? 'th' : 'td';
+ var cells = row.split('|').filter(function (c, ci, arr) { return ci > 0 && ci < arr.length - 1; });
+ out += '
';
+ cells.forEach(function (cell) { out += '<' + tag + '>' + cell.trim() + '' + tag + '>'; });
+ out += '
';
+ });
+ out += '
';
+ return out;
+ });
+ var lines = html.split('\n');
+ var result = [];
+ var inList = false;
+ var listType = '';
+ for (var i = 0; i < lines.length; i++) {
+ var line = lines[i];
+ if (line.indexOf('
';
+ }
+ popupImagePreviews.innerHTML = html;
+ popupImagePreviews.querySelectorAll('.popup-img-remove').forEach(function (btn) {
+ btn.addEventListener('click', function () {
+ popupRemoveImage(parseInt(btn.parentElement.getAttribute('data-idx')));
+ });
+ });
+ }
+
+ function popupUpdateImageUI() {
+ if (popupImageBtn) popupImageBtn.style.display = popupAgentImageUpload ? '' : 'none';
+ if (!popupAgentImageUpload && popupPendingImages.length > 0) popupClearImages();
+ }
+
+ function popupFileToBase64(file) {
+ return new Promise(function (resolve, reject) {
+ var reader = new FileReader();
+ reader.onload = function () { resolve(reader.result); };
+ reader.onerror = reject;
+ reader.readAsDataURL(file);
+ });
+ }
+
+ if (popupImageInput) {
+ popupImageInput.addEventListener('change', function () {
+ if (popupImageInput.files) popupAddImages(Array.from(popupImageInput.files));
+ popupImageInput.value = '';
+ });
+ }
+ if (popupImageBtn) {
+ popupImageBtn.addEventListener('click', function () {
+ if (popupImageInput) popupImageInput.click();
+ });
+ }
+
+ chatInput.addEventListener('paste', function (e) {
+ if (!popupAgentImageUpload) return;
+ var items = e.clipboardData && e.clipboardData.items;
+ if (!items) return;
+ var imageFiles = [];
+ for (var i = 0; i < items.length; i++) {
+ if (items[i].type.indexOf('image/') === 0) {
+ var f = items[i].getAsFile();
+ if (f) imageFiles.push(f);
+ }
+ }
+ if (imageFiles.length > 0) {
+ e.preventDefault();
+ popupAddImages(imageFiles);
+ }
+ });
chatInput.addEventListener('input', function () {
sendBtn.classList.toggle('active', chatInput.value.trim().length > 0);
+ // 自动调整高度
+ chatInput.style.height = 'auto';
+ chatInput.style.height = Math.min(chatInput.scrollHeight, 100) + 'px';
});
chatInput.addEventListener('keydown', function (e) {
@@ -367,6 +673,7 @@
e.preventDefault();
sendChat();
}
+ // Shift+Enter 默认行为即换行,无需额外处理
});
sendBtn.addEventListener('click', sendChat);
@@ -374,32 +681,48 @@
function sendChat() {
var text = chatInput.value.trim();
if (!text) return;
- var queryData = { query: text, user: currentUser, kb: selectedKb, mode: selectedMode, ts: Date.now() };
+ var queryData = { query: text, user: currentUser, kb: selectedKb, ts: Date.now(), agentId: popupAgentId, agentEnabled: popupAgentEnabled };
+ // 如果选中了具体知识库,传递知识库 ID
+ if (selectedKb && selectedKb !== 'all') {
+ queryData.knowledgeBaseIds = [selectedKb];
+ }
- if (chrome && chrome.storage) {
- chrome.storage.local.set({ ka_pending_query: queryData });
+ function doPopupSend(data) {
+ if (chrome && chrome.storage) {
+ chrome.storage.local.set({ ka_pending_query: data });
+ }
+ if (chrome && chrome.runtime && chrome.runtime.sendMessage) {
+ chrome.runtime.sendMessage({ type: 'CHAT_QUERY', payload: data }).catch(function () {});
+ }
+ if (chrome && chrome.tabs) {
+ chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
+ if (tabs && tabs[0]) {
+ chrome.sidePanel.open({ tabId: tabs[0].id }).catch(function () {});
+ }
+ window.close();
+ });
+ }
}
- if (chrome && chrome.runtime && chrome.runtime.sendMessage) {
- chrome.runtime.sendMessage({ type: 'CHAT_QUERY', payload: queryData }).catch(function () {});
- }
- if (chrome && chrome.tabs) {
- chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
- if (tabs && tabs[0]) {
- chrome.sidePanel.open({ tabId: tabs[0].id }).catch(function () {});
- }
- window.close();
+
+ if (popupPendingImages.length > 0) {
+ var promises = popupPendingImages.map(function (img) { return popupFileToBase64(img.file); });
+ Promise.all(promises).then(function (dataURIs) {
+ queryData.images = dataURIs.map(function (d) { return { data: d }; });
+ popupClearImages();
+ doPopupSend(queryData);
});
+ } else {
+ doPopupSend(queryData);
}
}
- // === 知识库下拉(合并模式选项) ===
+ // === 知识库下拉 ===
var kbMenu = $('kb-menu');
var kbBtn = $('btn-kb-select');
function positionKbMenu() {
var rect = kbBtn.getBoundingClientRect();
var menuH = kbMenu.offsetHeight;
- // 优先向上弹出;空间不足则向下
var top = rect.top - menuH - 6;
if (top < 4) top = rect.bottom + 6;
kbMenu.style.left = rect.left + 'px';
@@ -408,10 +731,10 @@
kbBtn.addEventListener('click', function (e) {
e.stopPropagation();
+ popupModeMenu.classList.remove('show');
var willShow = !kbMenu.classList.contains('show');
kbMenu.classList.toggle('show');
if (willShow) {
- // 先显示再计算高度
requestAnimationFrame(positionKbMenu);
}
});
@@ -427,20 +750,38 @@
kbMenu.classList.remove('show');
});
});
- // 模式选择(合并在知识库菜单内)
- kbMenu.querySelectorAll('.kb-mode-item').forEach(function (item) {
- item.addEventListener('click', function (e) {
- e.stopPropagation();
- selectedMode = item.getAttribute('data-mode');
- kbMenu.querySelectorAll('.kb-mode-item').forEach(function (i) { i.classList.remove('selected'); });
- item.classList.add('selected');
- kbMenu.classList.remove('show');
- });
+
+ // === 模式下拉(独立) ===
+ var popupModeMenu = $('popup-mode-menu');
+ var modeBtn = $('btn-mode-select');
+
+ function positionModeMenu() {
+ var rect = modeBtn.getBoundingClientRect();
+ var menuH = popupModeMenu.offsetHeight;
+ var top = rect.top - menuH - 6;
+ if (top < 4) top = rect.bottom + 6;
+ popupModeMenu.style.left = rect.left + 'px';
+ popupModeMenu.style.top = top + 'px';
+ }
+
+ modeBtn.addEventListener('click', function (e) {
+ e.stopPropagation();
+ kbMenu.classList.remove('show');
+ var willShow = !popupModeMenu.classList.contains('show');
+ popupModeMenu.classList.toggle('show');
+ if (willShow) {
+ requestAnimationFrame(positionModeMenu);
+ }
+ });
+
+ popupModeMenu.addEventListener('click', function (e) {
+ e.stopPropagation();
});
// 点击其他地方关闭下拉
document.addEventListener('click', function () {
kbMenu.classList.remove('show');
+ popupModeMenu.classList.remove('show');
if (moreMenu) moreMenu.classList.remove('show');
});
@@ -586,61 +927,186 @@
function renderMarkdown(text) {
if (!text) return '';
- var html = text;
- html = html.replace(/```(\w*)\n([\s\S]*?)```/g, function (_, lang, code) {
- return '
' + escapeHtml(code.replace(/\n$/, '')) + '
';
+
+ // 1. 提取代码块,替换为占位符
+ var codeBlocks = [];
+ var processed = text.replace(/```(\w*)\n([\s\S]*?)```/g, function (_, lang, code) {
+ var idx = codeBlocks.length;
+ codeBlocks.push('
' + escapeHtml(code.replace(/\n$/, '')) + '
');
+ return '\x00CODEBLOCK' + idx + '\x00';
});
- html = html.replace(/`([^`]+)`/g, '$1');
- html = html.replace(/((?:\|.+\|\n)+)/g, function (tableBlock) {
+
+ // 2. 提取行内代码
+ var inlineCodes = [];
+ processed = processed.replace(/`([^`]+)`/g, function (_, code) {
+ var idx = inlineCodes.length;
+ inlineCodes.push('' + escapeHtml(code) + '');
+ return '\x00INLINE' + idx + '\x00';
+ });
+
+ // 3. 表格处理 — 提取为占位符
+ var tables = [];
+ processed = processed.replace(/((?:\|.+\|\n)+)/g, function (tableBlock) {
var rows = tableBlock.trim().split('\n');
if (rows.length < 2) return tableBlock;
- var out = '
';
+ var out = '
';
rows.forEach(function (row, i) {
if (/^\|[\s\-:|]+\|$/.test(row)) return;
var tag = i === 0 ? 'th' : 'td';
var cells = row.split('|').filter(function (c, ci, arr) { return ci > 0 && ci < arr.length - 1; });
out += '
';
- cells.forEach(function (cell) { out += '<' + tag + '>' + cell.trim() + '' + tag + '>'; });
+ cells.forEach(function (cell) {
+ out += '<' + tag + '>' + cell.trim() + '' + tag + '>';
+ });
out += '
';
});
out += '
';
- return out;
+ var idx = tables.length;
+ tables.push(out);
+ return '\n\x00TABLE' + idx + '\x00\n';
});
- var lines = html.split('\n');
- var result = [];
- var inList = false;
- var listType = '';
- for (var i = 0; i < lines.length; i++) {
+
+ // 4. 逐行解析为块元素
+ var lines = processed.split('\n');
+ var html = '';
+ var i = 0;
+
+ while (i < lines.length) {
var line = lines[i];
- if (line.indexOf('
') !== -1 || line.indexOf('
') !== -1) {
- if (inList) { result.push('' + listType + '>'); inList = false; }
- result.push(line); continue;
+
+ // 代码块占位符
+ var cbMatch = line.match(/^\x00CODEBLOCK(\d+)\x00$/);
+ if (cbMatch) {
+ html += codeBlocks[parseInt(cbMatch[1])];
+ i++; continue;
}
- if (/^####\s+(.+)/.test(line)) { if (inList) { result.push('' + listType + '>'); inList = false; } result.push('
' + RegExp.$1 + '
'); continue; }
- if (/^###\s+(.+)/.test(line)) { if (inList) { result.push('' + listType + '>'); inList = false; } result.push('
' + RegExp.$1 + '
'); continue; }
- if (/^##\s+(.+)/.test(line)) { if (inList) { result.push('' + listType + '>'); inList = false; } result.push('
' + RegExp.$1 + '
'); continue; }
- if (/^#\s+(.+)/.test(line)) { if (inList) { result.push('' + listType + '>'); inList = false; } result.push('
' + RegExp.$1 + '
'); continue; }
- if (/^---+$/.test(line.trim())) { if (inList) { result.push('' + listType + '>'); inList = false; } result.push(''); continue; }
- if (/^>\s*(.*)/.test(line)) { if (inList) { result.push('' + listType + '>'); inList = false; } result.push('
' + RegExp.$1 + '
'); continue; }
- if (/^[\-\*]\s+(.+)/.test(line)) {
- if (!inList || listType !== 'ul') { if (inList) result.push('' + listType + '>'); result.push('
';
+ });
+ html = html.replace(/`([^`]+)`/g, '$1');
+ html = html.replace(/((?:\|.+\|\n)+)/g, function (tableBlock) {
+ var rows = tableBlock.trim().split('\n');
+ if (rows.length < 2) return tableBlock;
+ var out = '
';
+ rows.forEach(function (row, i) {
+ if (/^\|[\s\-:|]+\|$/.test(row)) return;
+ var tag = i === 0 ? 'th' : 'td';
+ var cells = row.split('|').filter(function (c, ci, arr) { return ci > 0 && ci < arr.length - 1; });
+ out += '
';
+ cells.forEach(function (cell) { out += '<' + tag + '>' + cell.trim() + '' + tag + '>'; });
+ out += '
';
+ });
+ out += '
';
+ return out;
+ });
+ var lines = html.split('\n');
+ var result = [];
+ var inList = false;
+ var listType = '';
+ for (var i = 0; i < lines.length; i++) {
+ var line = lines[i];
+ if (line.indexOf('
';
+ }
+ popupImagePreviews.innerHTML = html;
+ popupImagePreviews.querySelectorAll('.popup-img-remove').forEach(function (btn) {
+ btn.addEventListener('click', function () {
+ popupRemoveImage(parseInt(btn.parentElement.getAttribute('data-idx')));
+ });
+ });
+ }
+
+ function popupUpdateImageUI() {
+ if (popupImageBtn) popupImageBtn.style.display = popupAgentImageUpload ? '' : 'none';
+ if (!popupAgentImageUpload && popupPendingImages.length > 0) popupClearImages();
+ }
+
+ function popupFileToBase64(file) {
+ return new Promise(function (resolve, reject) {
+ var reader = new FileReader();
+ reader.onload = function () { resolve(reader.result); };
+ reader.onerror = reject;
+ reader.readAsDataURL(file);
+ });
+ }
+
+ if (popupImageInput) {
+ popupImageInput.addEventListener('change', function () {
+ if (popupImageInput.files) popupAddImages(Array.from(popupImageInput.files));
+ popupImageInput.value = '';
+ });
+ }
+ if (popupImageBtn) {
+ popupImageBtn.addEventListener('click', function () {
+ if (popupImageInput) popupImageInput.click();
+ });
+ }
+
+ chatInput.addEventListener('paste', function (e) {
+ if (!popupAgentImageUpload) return;
+ var items = e.clipboardData && e.clipboardData.items;
+ if (!items) return;
+ var imageFiles = [];
+ for (var i = 0; i < items.length; i++) {
+ if (items[i].type.indexOf('image/') === 0) {
+ var f = items[i].getAsFile();
+ if (f) imageFiles.push(f);
+ }
+ }
+ if (imageFiles.length > 0) {
+ e.preventDefault();
+ popupAddImages(imageFiles);
+ }
+ });
chatInput.addEventListener('input', function () {
sendBtn.classList.toggle('active', chatInput.value.trim().length > 0);
+ // 自动调整高度
+ chatInput.style.height = 'auto';
+ chatInput.style.height = Math.min(chatInput.scrollHeight, 100) + 'px';
});
chatInput.addEventListener('keydown', function (e) {
@@ -367,6 +673,7 @@
e.preventDefault();
sendChat();
}
+ // Shift+Enter 默认行为即换行,无需额外处理
});
sendBtn.addEventListener('click', sendChat);
@@ -374,32 +681,48 @@
function sendChat() {
var text = chatInput.value.trim();
if (!text) return;
- var queryData = { query: text, user: currentUser, kb: selectedKb, mode: selectedMode, ts: Date.now() };
+ var queryData = { query: text, user: currentUser, kb: selectedKb, ts: Date.now(), agentId: popupAgentId, agentEnabled: popupAgentEnabled };
+ // 如果选中了具体知识库,传递知识库 ID
+ if (selectedKb && selectedKb !== 'all') {
+ queryData.knowledgeBaseIds = [selectedKb];
+ }
- if (chrome && chrome.storage) {
- chrome.storage.local.set({ ka_pending_query: queryData });
+ function doPopupSend(data) {
+ if (chrome && chrome.storage) {
+ chrome.storage.local.set({ ka_pending_query: data });
+ }
+ if (chrome && chrome.runtime && chrome.runtime.sendMessage) {
+ chrome.runtime.sendMessage({ type: 'CHAT_QUERY', payload: data }).catch(function () {});
+ }
+ if (chrome && chrome.tabs) {
+ chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
+ if (tabs && tabs[0]) {
+ chrome.sidePanel.open({ tabId: tabs[0].id }).catch(function () {});
+ }
+ window.close();
+ });
+ }
}
- if (chrome && chrome.runtime && chrome.runtime.sendMessage) {
- chrome.runtime.sendMessage({ type: 'CHAT_QUERY', payload: queryData }).catch(function () {});
- }
- if (chrome && chrome.tabs) {
- chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
- if (tabs && tabs[0]) {
- chrome.sidePanel.open({ tabId: tabs[0].id }).catch(function () {});
- }
- window.close();
+
+ if (popupPendingImages.length > 0) {
+ var promises = popupPendingImages.map(function (img) { return popupFileToBase64(img.file); });
+ Promise.all(promises).then(function (dataURIs) {
+ queryData.images = dataURIs.map(function (d) { return { data: d }; });
+ popupClearImages();
+ doPopupSend(queryData);
});
+ } else {
+ doPopupSend(queryData);
}
}
- // === 知识库下拉(合并模式选项) ===
+ // === 知识库下拉 ===
var kbMenu = $('kb-menu');
var kbBtn = $('btn-kb-select');
function positionKbMenu() {
var rect = kbBtn.getBoundingClientRect();
var menuH = kbMenu.offsetHeight;
- // 优先向上弹出;空间不足则向下
var top = rect.top - menuH - 6;
if (top < 4) top = rect.bottom + 6;
kbMenu.style.left = rect.left + 'px';
@@ -408,10 +731,10 @@
kbBtn.addEventListener('click', function (e) {
e.stopPropagation();
+ popupModeMenu.classList.remove('show');
var willShow = !kbMenu.classList.contains('show');
kbMenu.classList.toggle('show');
if (willShow) {
- // 先显示再计算高度
requestAnimationFrame(positionKbMenu);
}
});
@@ -427,20 +750,38 @@
kbMenu.classList.remove('show');
});
});
- // 模式选择(合并在知识库菜单内)
- kbMenu.querySelectorAll('.kb-mode-item').forEach(function (item) {
- item.addEventListener('click', function (e) {
- e.stopPropagation();
- selectedMode = item.getAttribute('data-mode');
- kbMenu.querySelectorAll('.kb-mode-item').forEach(function (i) { i.classList.remove('selected'); });
- item.classList.add('selected');
- kbMenu.classList.remove('show');
- });
+
+ // === 模式下拉(独立) ===
+ var popupModeMenu = $('popup-mode-menu');
+ var modeBtn = $('btn-mode-select');
+
+ function positionModeMenu() {
+ var rect = modeBtn.getBoundingClientRect();
+ var menuH = popupModeMenu.offsetHeight;
+ var top = rect.top - menuH - 6;
+ if (top < 4) top = rect.bottom + 6;
+ popupModeMenu.style.left = rect.left + 'px';
+ popupModeMenu.style.top = top + 'px';
+ }
+
+ modeBtn.addEventListener('click', function (e) {
+ e.stopPropagation();
+ kbMenu.classList.remove('show');
+ var willShow = !popupModeMenu.classList.contains('show');
+ popupModeMenu.classList.toggle('show');
+ if (willShow) {
+ requestAnimationFrame(positionModeMenu);
+ }
+ });
+
+ popupModeMenu.addEventListener('click', function (e) {
+ e.stopPropagation();
});
// 点击其他地方关闭下拉
document.addEventListener('click', function () {
kbMenu.classList.remove('show');
+ popupModeMenu.classList.remove('show');
if (moreMenu) moreMenu.classList.remove('show');
});
@@ -586,61 +927,186 @@
function renderMarkdown(text) {
if (!text) return '';
- var html = text;
- html = html.replace(/```(\w*)\n([\s\S]*?)```/g, function (_, lang, code) {
- return '
' + escapeHtml(code.replace(/\n$/, '')) + '
';
+
+ // 1. 提取代码块,替换为占位符
+ var codeBlocks = [];
+ var processed = text.replace(/```(\w*)\n([\s\S]*?)```/g, function (_, lang, code) {
+ var idx = codeBlocks.length;
+ codeBlocks.push('
' + escapeHtml(code.replace(/\n$/, '')) + '
');
+ return '\x00CODEBLOCK' + idx + '\x00';
});
- html = html.replace(/`([^`]+)`/g, '$1');
- html = html.replace(/((?:\|.+\|\n)+)/g, function (tableBlock) {
+
+ // 2. 提取行内代码
+ var inlineCodes = [];
+ processed = processed.replace(/`([^`]+)`/g, function (_, code) {
+ var idx = inlineCodes.length;
+ inlineCodes.push('' + escapeHtml(code) + '');
+ return '\x00INLINE' + idx + '\x00';
+ });
+
+ // 3. 表格处理 — 提取为占位符
+ var tables = [];
+ processed = processed.replace(/((?:\|.+\|\n)+)/g, function (tableBlock) {
var rows = tableBlock.trim().split('\n');
if (rows.length < 2) return tableBlock;
- var out = '
';
+ var out = '
';
rows.forEach(function (row, i) {
if (/^\|[\s\-:|]+\|$/.test(row)) return;
var tag = i === 0 ? 'th' : 'td';
var cells = row.split('|').filter(function (c, ci, arr) { return ci > 0 && ci < arr.length - 1; });
out += '
';
- cells.forEach(function (cell) { out += '<' + tag + '>' + cell.trim() + '' + tag + '>'; });
+ cells.forEach(function (cell) {
+ out += '<' + tag + '>' + cell.trim() + '' + tag + '>';
+ });
out += '
';
});
out += '
';
- return out;
+ var idx = tables.length;
+ tables.push(out);
+ return '\n\x00TABLE' + idx + '\x00\n';
});
- var lines = html.split('\n');
- var result = [];
- var inList = false;
- var listType = '';
- for (var i = 0; i < lines.length; i++) {
+
+ // 4. 逐行解析为块元素
+ var lines = processed.split('\n');
+ var html = '';
+ var i = 0;
+
+ while (i < lines.length) {
var line = lines[i];
- if (line.indexOf('
') !== -1 || line.indexOf('
') !== -1) {
- if (inList) { result.push('' + listType + '>'); inList = false; }
- result.push(line); continue;
+
+ // 代码块占位符
+ var cbMatch = line.match(/^\x00CODEBLOCK(\d+)\x00$/);
+ if (cbMatch) {
+ html += codeBlocks[parseInt(cbMatch[1])];
+ i++; continue;
}
- if (/^####\s+(.+)/.test(line)) { if (inList) { result.push('' + listType + '>'); inList = false; } result.push('
' + RegExp.$1 + '
'); continue; }
- if (/^###\s+(.+)/.test(line)) { if (inList) { result.push('' + listType + '>'); inList = false; } result.push('
' + RegExp.$1 + '
'); continue; }
- if (/^##\s+(.+)/.test(line)) { if (inList) { result.push('' + listType + '>'); inList = false; } result.push('
' + RegExp.$1 + '
'); continue; }
- if (/^#\s+(.+)/.test(line)) { if (inList) { result.push('' + listType + '>'); inList = false; } result.push('
' + RegExp.$1 + '
'); continue; }
- if (/^---+$/.test(line.trim())) { if (inList) { result.push('' + listType + '>'); inList = false; } result.push(''); continue; }
- if (/^>\s*(.*)/.test(line)) { if (inList) { result.push('' + listType + '>'); inList = false; } result.push('
' + RegExp.$1 + '
'); continue; }
- if (/^[\-\*]\s+(.+)/.test(line)) {
- if (!inList || listType !== 'ul') { if (inList) result.push('' + listType + '>'); result.push('
- ```
-
- The `.icon_box` and `.download_box` CSS classes are already defined in this component (used by the `file` type block above).
-
-- [ ] **Step 3: Fix the link.download attribute and a pre-existing removeChild bug in downloadFile()**
-
- In the same file, locate `downloadFile()` at lines 619–641.
-
- **Fix 1 — filename extension (line 630).** The current line is:
-
- ```ts
- link.setAttribute("download", props.details.title);
- ```
-
- Replace it with:
-
- ```ts
- link.setAttribute("download", props.details.type === 'manual' ? props.details.title + '.md' : props.details.title);
- ```
-
- **Fix 2 — pre-existing removeChild bug (line 633).** The link is created but never appended to `document.body`, so `document.body.removeChild(link)` throws a DOM exception at runtime. While fixing this is strictly out of scope, you will be touching this function anyway, so add the missing `appendChild` call right before `link.click()`:
-
- Before `link.click()`, add:
- ```ts
- document.body.appendChild(link);
- ```
-
- The full corrected block (lines 627–635) should read:
-
- ```ts
- const link = document.createElement("a");
- link.style.display = "none";
- link.setAttribute("href", url.value);
- link.setAttribute("download", props.details.type === 'manual' ? props.details.title + '.md' : props.details.title);
- document.body.appendChild(link);
- link.click();
- nextTick(() => {
- document.body.removeChild(link);
- URL.revokeObjectURL(url.value);
- })
- ```
-
-- [ ] **Step 4: Run TypeScript type check**
-
- ```bash
- cd frontend && npm run type-check
- ```
-
- Expected: exits 0, no type errors.
-
-- [ ] **Step 5: Commit**
-
- ```bash
- git add frontend/src/components/doc-content.vue
- git commit -m "feat: add download button for manual knowledge in doc-content"
- ```
-
----
-
-## Manual Smoke Test (after both tasks)
-
-Start the dev server and verify end-to-end:
-
-1. Open a knowledge base that contains a `manual` type knowledge item.
-2. Navigate to the knowledge detail page — confirm the download icon is visible (same icon as file type).
-3. Click the download icon.
-4. Verify the browser downloads a file named `{title}.md`.
-5. Open the file and confirm the contents match the Markdown content in the editor.
-6. Edge cases to spot-check:
- - Knowledge item with empty content → downloads an empty `.md` file (not an error).
- - Knowledge item whose title contains `/` or `"` → filename has `-` or `'` substituted respectively.
diff --git a/docs/superpowers/specs/2026-03-16-manual-knowledge-download-design.md b/docs/superpowers/specs/2026-03-16-manual-knowledge-download-design.md
deleted file mode 100644
index c11ed42e..00000000
--- a/docs/superpowers/specs/2026-03-16-manual-knowledge-download-design.md
+++ /dev/null
@@ -1,132 +0,0 @@
-# Manual Knowledge Download — Design Spec
-
-**Date:** 2026-03-16
-**Status:** Approved
-
----
-
-## Background
-
-WeKnora supports multiple knowledge types. The `manual` type stores content as Markdown in the database `Metadata.content` field — there is no physical file on disk or in object storage. The existing download endpoint (`GET /api/v1/knowledge/:id/download`) only works for `file` type knowledge; calling it for `manual` type would silently fail with an internal error because `FilePath` is empty.
-
-The frontend `doc-content.vue` component already omits the download button for `manual` type knowledge. This spec describes how to add proper download support.
-
----
-
-## Goal
-
-Allow users to download `manual` type knowledge as a `.md` file whose content is the Markdown stored in `Metadata.content` and whose filename is `{title}.md`.
-
----
-
-## Architecture
-
-### Backend — `internal/application/service/knowledge.go`
-
-**Method:** `GetKnowledgeFile(ctx, id) (io.ReadCloser, string, error)`
-
-Add an early-return branch before the existing file-service lookup:
-
-```go
-if knowledge.IsManual() {
- meta, err := knowledge.ManualMetadata()
- if err != nil {
- return nil, "", err
- }
- // ManualMetadata returns (nil, nil) when Metadata column is empty;
- // treat as empty content rather than an error.
- content := ""
- if meta != nil {
- content = meta.Content
- }
- // Sanitize title for use as a filename: strip newlines and path separators.
- safeName := strings.NewReplacer(
- "\n", "", "\r", "", "/", "-", "\\", "-", "\"", "'",
- ).Replace(knowledge.Title)
- filename := safeName + ".md"
- return io.NopCloser(strings.NewReader(content)), filename, nil
-}
-```
-
-- No new routes, handlers, or services required.
-- All existing permission checks, logging, and error middleware remain intact.
-- The handler sets `Content-Disposition: attachment; filename="{safeName}.md"` via the existing streaming logic.
-
-#### Non-ASCII filenames in `Content-Disposition`
-
-The existing handler writes the filename unquoted and without RFC 5987 encoding (`filename*=UTF-8''...`). This is a **known limitation inherited from the existing file-type download path** and is out of scope for this change. Most modern browsers (Chrome, Edge, Firefox) tolerate unquoted UTF-8 values in practice. A follow-up issue should address RFC 5987 encoding for all download types.
-
-### Frontend — `frontend/src/components/doc-content.vue`
-
-Two changes are required:
-
-**1. Add download button to the `manual` UI block:**
-
-```vue
-