diff --git a/frontend/src/api/knowledge-base/index.ts b/frontend/src/api/knowledge-base/index.ts index 0a37041e..56ab31b1 100644 --- a/frontend/src/api/knowledge-base/index.ts +++ b/frontend/src/api/knowledge-base/index.ts @@ -258,6 +258,7 @@ export function uploadKnowledgeFile( [key: string]: any } = { file: new File([], '') }, onProgress?: (progressEvent: any) => void, + config?: { signal?: AbortSignal }, ) { const formData = new FormData(); Object.keys(data).forEach(key => { @@ -271,7 +272,7 @@ export function uploadKnowledgeFile( formData.append(key, value); } }); - return postUpload(`/api/v1/knowledge-bases/${kbId}/knowledge/file`, formData, onProgress); + return postUpload(`/api/v1/knowledge-bases/${kbId}/knowledge/file`, formData, onProgress, config); } // 从URL创建知识 diff --git a/frontend/src/components/upload-tasks/ProgressRing.vue b/frontend/src/components/upload-tasks/ProgressRing.vue new file mode 100644 index 00000000..4a3ff41c --- /dev/null +++ b/frontend/src/components/upload-tasks/ProgressRing.vue @@ -0,0 +1,67 @@ + + + + + diff --git a/frontend/src/components/upload-tasks/UploadTaskRow.vue b/frontend/src/components/upload-tasks/UploadTaskRow.vue new file mode 100644 index 00000000..b1d7780d --- /dev/null +++ b/frontend/src/components/upload-tasks/UploadTaskRow.vue @@ -0,0 +1,308 @@ + + + + + diff --git a/frontend/src/components/upload-tasks/UploadTasksPanel.vue b/frontend/src/components/upload-tasks/UploadTasksPanel.vue new file mode 100644 index 00000000..11bcf369 --- /dev/null +++ b/frontend/src/components/upload-tasks/UploadTasksPanel.vue @@ -0,0 +1,720 @@ + + + + + diff --git a/frontend/src/hooks/useKnowledgeBase.ts b/frontend/src/hooks/useKnowledgeBase.ts index ec5dba67..8455eac9 100644 --- a/frontend/src/hooks/useKnowledgeBase.ts +++ b/frontend/src/hooks/useKnowledgeBase.ts @@ -1,15 +1,12 @@ import { ref, reactive } from "vue"; import { storeToRefs } from "pinia"; -import { formatStringDate, kbFileTypeVerification } from "../utils/index"; -import { MessagePlugin } from "tdesign-vue-next"; +import { formatStringDate } from "../utils/index"; import { - uploadKnowledgeFile, listKnowledgeFiles, getKnowledgeDetails, getKnowledgeDetailsCon, } from "@/api/knowledge-base/index"; import { knowledgeStore } from "@/stores/knowledge"; -import { useUIStore } from "@/stores/ui"; import { useRoute } from 'vue-router'; import { useI18n } from 'vue-i18n'; @@ -103,51 +100,6 @@ export default function (knowledgeBaseId?: string) { moreIndex.value = -1; } }; - const requestMethod = (file: any, uploadInput: any) => { - if (!(file instanceof File) || !uploadInput) { - MessagePlugin.error(t('error.invalidFileType')); - return; - } - - if (kbFileTypeVerification(file)) { - return; - } - - // 获取当前知识库ID - let currentKbId: string | undefined = (route.params as any)?.kbId as string; - if (!currentKbId && typeof window !== 'undefined') { - const match = window.location.pathname.match(/knowledge-bases\/([^/]+)/); - if (match?.[1]) currentKbId = match[1]; - } - if (!currentKbId) { - currentKbId = knowledgeBaseId; - } - if (!currentKbId) { - MessagePlugin.error(t('error.missingKbId')); - return; - } - - // 获取当前选中的标签 ID - const uiStore = useUIStore(); - const tagIdsToUpload = uiStore.selectedTagIds.length > 0 ? [...uiStore.selectedTagIds] : undefined; - - uploadKnowledgeFile(currentKbId, { file, tag_ids: tagIdsToUpload }) - .then((result: any) => { - if (result.success) { - MessagePlugin.info(t('knowledgeBase.uploadSuccess')); - getKnowled({ page: 1, page_size: 35 }, currentKbId); - } else { - const errorMessage = result.error?.message || result.message || t('knowledgeBase.uploadFailed'); - MessagePlugin.error(result.code === 'duplicate_file' ? t('knowledgeBase.fileExists') : errorMessage); - } - uploadInput.value.value = ""; - }) - .catch((err: any) => { - const errorMessage = err.error?.message || err.message || t('knowledgeBase.uploadFailed'); - MessagePlugin.error(err.code === 'duplicate_file' ? t('knowledgeBase.fileExists') : errorMessage); - uploadInput.value.value = ""; - }); - }; const getCardDetails = (item: any) => { activeKnowledgeId = item.id; chunkRequestGeneration++; @@ -230,7 +182,6 @@ export default function (knowledgeBaseId?: string) { details, openMore, onVisibleChange, - requestMethod, getCardDetails, total, getfDetails, diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 08cc6e1e..c22b582d 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -589,13 +589,6 @@ export default { tagLabel: 'Tag', tagPlaceholder: 'Select tags', noTags: 'No tags', - uploadSuccess: 'File uploaded successfully!', - uploadFailed: 'File upload failed!', - fileExists: 'File already exists', - uploadAllSuccess: 'Successfully uploaded {count} files!', - uploadPartialSuccess: 'Upload completed: {success} succeeded, {fail} failed', - uploadAllFailed: 'All files failed to upload', - uploadingFolder: 'Uploading {total} files from folder...', videosFilteredNoVLM: 'Skipped {count} video file(s) (video upload is not supported)', unsupportedTypesHint: 'Some document types ({types}) have no available parser engine and cannot be processed', goToParserSettings: 'Configure', @@ -822,9 +815,6 @@ export default { operationNotSupportedForType: 'This operation is not supported for the current knowledge base type', allFilesSkippedNoEngine: 'All selected files were skipped due to no available parser engine', filesSkippedNoEngine: '{count} file(s) skipped due to no available parser engine', - allUploadSuccess: 'All files uploaded successfully ({count} files)', - partialUploadSuccess: 'Partial upload success (success: {success}, failed: {fail})', - allUploadFailed: 'All files failed to upload ({count} files)', deleteSuccess: 'Knowledge deleted successfully!', chunkLoadFailed: 'Failed to load chunks' }, @@ -2755,16 +2745,6 @@ export default { questionGeneration: 'Question Generation', wiki: 'Wiki' }, - uploadProgress: { - uploadingTitle: 'Uploading folder documents to "{name}"', - detail: '{completed}/{total} files finished', - keepPageOpen: 'Please keep this page open while files upload.', - completedTitle: 'Upload finished for "{name}"', - completedDetail: 'All {total} files uploaded. Refreshing list to show parsing status...', - refreshing: 'Refreshing list to show parsing status...', - errorTip: 'Some files failed to upload. Please check the notifications.', - unknownKb: 'Knowledge Base {id}' - } }, embedPublish: { create: 'New embed channel', @@ -4890,6 +4870,55 @@ export default { onlineEdit: 'Online Edit', deleteRecord: 'Delete Record' }, + uploadTasks: { + panelLabel: 'Uploads', + titleUploading: 'Uploading {done} of {total}', + titleParsing: 'Parsing {done} of {total}', + titleDone: 'All done', + titleDoneWithIssues: '{ok} done, {bad} not completed', + titleCancelled: 'Upload cancelled', + destination: 'Destination: {name}', + destinationMany: 'Destination: {count} knowledge bases', + remaining: 'about {time} left', + eta: { + seconds: '{n} sec', + minutes: '{n} min', + hours: '{n} hr' + }, + hintUploading: 'Keep this page open until the upload finishes', + hintParsing: 'All files are uploaded. Parsing continues in the background, so you can leave this page', + legend: { + ready: 'Searchable', + active: 'In progress', + waiting: 'Queued', + failed: 'Failed', + duplicate: 'Already exists' + }, + filterAll: 'All', + filterIssues: 'Not completed', + phaseWaiting: 'Queued', + phaseSaving: 'Saving…', + phasePending: 'Waiting to parse', + phaseParsing: 'Parsing', + phaseFinalizing: 'Searchable, still optimizing', + phaseReady: 'Done', + phaseUploadFailed: 'Upload failed', + phaseParseFailed: 'Parsing failed', + phaseDuplicate: 'Same file already in this knowledge base', + phaseCancelled: 'Cancelled', + phaseDeleted: 'Deleted', + cancel: 'Cancel', + cancelAll: 'Cancel all', + retry: 'Retry', + retryFailed: 'Retry ({count})', + open: 'Open', + collapse: 'Collapse', + expand: 'Expand', + close: 'Close', + closeConfirm: 'Closing stops the unfinished uploads ({count})', + closeConfirmOk: 'Cancel upload', + closeConfirmKeep: 'Keep uploading' + }, agentSettings: { modelRecommendation: { title: 'Model Recommendation' diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts index a4a36538..dfb3eace 100644 --- a/frontend/src/i18n/locales/ja-JP.ts +++ b/frontend/src/i18n/locales/ja-JP.ts @@ -589,13 +589,6 @@ export default { tagLabel: 'タグ', tagPlaceholder: 'タグを選択', noTags: 'タグなし', - uploadSuccess: 'ファイルをアップロードしました。', - uploadFailed: 'ファイルのアップロードに失敗しました。', - fileExists: 'ファイルは既に存在します', - uploadAllSuccess: '{count}件のファイルをアップロードしました。', - uploadPartialSuccess: 'アップロード完了: 成功{success}件、失敗{fail}件', - uploadAllFailed: 'すべてのファイルのアップロードに失敗しました', - uploadingFolder: 'フォルダ内の{total}件のファイルをアップロード中...', videosFilteredNoVLM: '{count}件の動画ファイルをスキップしました(動画のアップロードには対応していません)', unsupportedTypesHint: '一部のドキュメント形式({types})は利用できる解析エンジンがないため、アップロードしても解析できません', goToParserSettings: '設定を開く', @@ -822,9 +815,6 @@ export default { operationNotSupportedForType: 'この操作は現在のナレッジベースのタイプでは利用できません', allFilesSkippedNoEngine: '利用可能な解析エンジンがないため、選択したすべてのファイルをスキップしました', filesSkippedNoEngine: '利用可能な解析エンジンがないため、{count}件のファイルをスキップしました', - allUploadSuccess: 'すべてのファイルをアップロードしました({count}件)', - partialUploadSuccess: '一部のファイルをアップロードしました(成功: {success}件、失敗: {fail}件)', - allUploadFailed: 'すべてのファイルのアップロードに失敗しました({count}件)', deleteSuccess: 'ナレッジを削除しました。', chunkLoadFailed: 'チャンクの読み込みに失敗しました' }, @@ -2755,16 +2745,6 @@ export default { questionGeneration: '質問生成', wiki: 'Wiki' }, - uploadProgress: { - uploadingTitle: '「{name}」にフォルダ内のドキュメントをアップロード中', - detail: '{completed}/{total}ファイル完了', - keepPageOpen: 'アップロード中はこのページを開いたままにしてください。', - completedTitle: '「{name}」へのアップロードが完了しました', - completedDetail: '{total}件のファイルをすべてアップロードしました。解析ステータスを表示するため一覧を更新しています...', - refreshing: '解析ステータスを表示するため一覧を更新しています...', - errorTip: '一部のファイルのアップロードに失敗しました。通知を確認してください。', - unknownKb: 'ナレッジベース{id}' - } }, embedPublish: { create: '埋め込みチャネルを作成', @@ -4890,6 +4870,55 @@ export default { onlineEdit: 'オンライン編集', deleteRecord: '記録を削除' }, + uploadTasks: { + panelLabel: 'アップロード', + titleUploading: 'アップロード中 {done}/{total}', + titleParsing: '解析中 {done}/{total}', + titleDone: 'すべて完了', + titleDoneWithIssues: '{ok}件完了、{bad}件未完了', + titleCancelled: 'アップロードをキャンセルしました', + destination: 'アップロード先:{name}', + destinationMany: 'アップロード先:{count}件のナレッジベース', + remaining: '残り約{time}', + eta: { + seconds: '{n}秒', + minutes: '{n}分', + hours: '{n}時間' + }, + hintUploading: 'アップロードが完了するまでページを閉じたり再読み込みしたりしないでください', + hintParsing: 'すべてのファイルをアップロードしました。解析はバックグラウンドで続くため、このページを離れても問題ありません', + legend: { + ready: '検索可能', + active: '処理中', + waiting: '待機中', + failed: '失敗', + duplicate: '既存' + }, + filterAll: 'すべて', + filterIssues: '未完了', + phaseWaiting: 'アップロード待ち', + phaseSaving: '保存中…', + phasePending: '解析待ち', + phaseParsing: '解析中', + phaseFinalizing: '検索可能・バックグラウンドで最適化中', + phaseReady: '完了', + phaseUploadFailed: 'アップロード失敗', + phaseParseFailed: '解析失敗', + phaseDuplicate: '同じファイルが既にあります', + phaseCancelled: 'キャンセル済み', + phaseDeleted: '削除済み', + cancel: 'キャンセル', + cancelAll: 'すべてキャンセル', + retry: '再試行', + retryFailed: '{count}件を再試行', + open: '開く', + collapse: '折りたたむ', + expand: '展開', + close: '閉じる', + closeConfirm: '閉じると、残り{count}件のアップロードがキャンセルされます', + closeConfirmOk: 'アップロードをキャンセル', + closeConfirmKeep: 'アップロードを続ける' + }, agentSettings: { modelRecommendation: { title: '推奨モデル' diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index cd082a28..ca95ad2b 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -2606,6 +2606,55 @@ export default { onlineEdit: '온라인 편집', deleteRecord: '기록 삭제' }, + uploadTasks: { + panelLabel: '업로드', + titleUploading: '업로드 중 {done}/{total}', + titleParsing: '파싱 중 {done}/{total}', + titleDone: '모두 완료', + titleDoneWithIssues: '{ok}개 완료, {bad}개 미완료', + titleCancelled: '업로드가 취소되었습니다', + destination: '업로드 위치: {name}', + destinationMany: '업로드 위치: 지식베이스 {count}개', + remaining: '약 {time} 남음', + eta: { + seconds: '{n}초', + minutes: '{n}분', + hours: '{n}시간' + }, + hintUploading: '업로드가 끝날 때까지 페이지를 닫거나 새로고침하지 마세요', + hintParsing: '모든 파일이 업로드되었습니다. 파싱은 백그라운드에서 계속되므로 이 페이지를 떠나도 됩니다', + legend: { + ready: '검색 가능', + active: '처리 중', + waiting: '대기 중', + failed: '실패', + duplicate: '이미 있음' + }, + filterAll: '전체', + filterIssues: '미완료', + phaseWaiting: '업로드 대기', + phaseSaving: '저장 중…', + phasePending: '파싱 대기', + phaseParsing: '파싱 중', + phaseFinalizing: '검색 가능, 백그라운드 최적화 중', + phaseReady: '완료', + phaseUploadFailed: '업로드 실패', + phaseParseFailed: '파싱 실패', + phaseDuplicate: '동일한 파일이 이미 있습니다', + phaseCancelled: '취소됨', + phaseDeleted: '삭제됨', + cancel: '취소', + cancelAll: '모두 취소', + retry: '다시 시도', + retryFailed: '{count}개 다시 시도', + open: '열기', + collapse: '접기', + expand: '펼치기', + close: '닫기', + closeConfirm: '닫으면 남은 {count}개 파일의 업로드가 취소됩니다', + closeConfirmOk: '업로드 취소', + closeConfirmKeep: '계속 업로드' + }, time: { today: '오늘', yesterday: '어제', @@ -4729,16 +4778,6 @@ export default { subtitle: '지식베이스를 관리하고 구성합니다. 문서형과 Q&A형 지식베이스를 지원합니다', sharedToOrgs: '{count} 스페이스에 공유됨', uninitializedBanner: '일부 지식베이스가 아직 초기화되지 않았습니다. 지식 문서를 추가하려면 먼저 설정에서 모델 정보를 구성해야 합니다', - uploadProgress: { - uploadingTitle: '「{name}」에 폴더의 문서 업로드 중', - detail: '{completed}/{total}개 파일 완료', - keepPageOpen: '페이지를 열어두세요. 업로드가 완료되면 파싱 상태가 자동으로 새로고침됩니다.', - completedTitle: '「{name}」 업로드 완료', - completedDetail: '총 {total}개 파일이 업로드되었습니다. 파싱 상태를 확인하기 위해 목록을 새로고침하는 중...', - refreshing: '목록을 새로고침하고 최신 파싱 상태를 가져오는 중...', - errorTip: '일부 파일 업로드에 실패했습니다. 오른쪽 상단의 알림 세부 정보를 확인해주세요.', - unknownKb: '지식베이스 {id}' - }, features: { knowledgeGraph: '지식 그래프 활성화됨', multimodal: '멀티모달 활성화됨', @@ -6733,13 +6772,6 @@ export default { tagLabel: '태그', tagPlaceholder: '태그를 선택하세요', noTags: '태그 없음', - uploadSuccess: '파일 업로드 성공!', - uploadFailed: '파일 업로드 실패!', - fileExists: '파일이 이미 존재합니다', - uploadAllSuccess: '{count}개 파일 업로드 성공!', - uploadPartialSuccess: '업로드 완료: 성공 {success}개, 실패 {fail}개', - uploadAllFailed: '모든 파일 업로드 실패', - uploadingFolder: '폴더의 {total}개 파일 업로드 중...', videosFilteredNoVLM: '{count}개의 동영상 파일을 건너됨 (동영상 업로드 미지원)', unsupportedTypesHint: '일부 문서 유형({types})에 사용 가능한 파서 엔진이 없어 처리할 수 없습니다', goToParserSettings: '설정으로 이동', @@ -6966,9 +6998,6 @@ export default { operationNotSupportedForType: '현재 지식베이스 유형에서는 이 작업을 지원하지 않습니다', allFilesSkippedNoEngine: '선택한 모든 파일이 사용 가능한 파싱 엔진이 없어 건너뛰었습니다', filesSkippedNoEngine: '{count}개 파일이 사용 가능한 파싱 엔진이 없어 건너뛰었습니다', - allUploadSuccess: '모든 파일 업로드 성공 ({count}개)', - partialUploadSuccess: '일부 파일 업로드 성공 (성공: {success}, 실패: {fail})', - allUploadFailed: '모든 파일 업로드 실패 ({count}개)', deleteSuccess: '지식이 성공적으로 삭제되었습니다!', chunkLoadFailed: '청크 로드 실패', infoCard: { diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 350308e9..c5f0d89d 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -2606,6 +2606,55 @@ export default { onlineEdit: 'Онлайн редактирование', deleteRecord: 'Удалить запись' }, + uploadTasks: { + panelLabel: 'Загрузки', + titleUploading: 'Загрузка {done} из {total}', + titleParsing: 'Разбор {done} из {total}', + titleDone: 'Готово', + titleDoneWithIssues: 'Готово: {ok}, не завершено: {bad}', + titleCancelled: 'Загрузка отменена', + destination: 'Куда: {name}', + destinationMany: 'Куда: баз знаний — {count}', + remaining: 'осталось около {time}', + eta: { + seconds: '{n} с', + minutes: '{n} мин', + hours: '{n} ч' + }, + hintUploading: 'Не закрывайте и не обновляйте страницу до завершения загрузки', + hintParsing: 'Все файлы загружены. Разбор продолжится в фоне — страницу можно закрыть', + legend: { + ready: 'Доступно для поиска', + active: 'В работе', + waiting: 'В очереди', + failed: 'Ошибка', + duplicate: 'Уже есть' + }, + filterAll: 'Все', + filterIssues: 'Не завершено', + phaseWaiting: 'В очереди', + phaseSaving: 'Сохранение…', + phasePending: 'Ожидает разбора', + phaseParsing: 'Разбор', + phaseFinalizing: 'Доступно для поиска, идёт оптимизация', + phaseReady: 'Готово', + phaseUploadFailed: 'Ошибка загрузки', + phaseParseFailed: 'Ошибка разбора', + phaseDuplicate: 'Такой файл уже есть', + phaseCancelled: 'Отменено', + phaseDeleted: 'Удалено', + cancel: 'Отменить', + cancelAll: 'Отменить все', + retry: 'Повторить', + retryFailed: 'Повторить ({count})', + open: 'Открыть', + collapse: 'Свернуть', + expand: 'Развернуть', + close: 'Закрыть', + closeConfirm: 'Закрытие отменит загрузку оставшихся файлов ({count})', + closeConfirmOk: 'Отменить загрузку', + closeConfirmKeep: 'Продолжить загрузку' + }, time: { today: 'Сегодня', yesterday: 'Вчера', @@ -4729,16 +4778,6 @@ export default { subtitle: 'Управляйте и организуйте свои базы знаний, поддерживаются документные и FAQ-базы знаний', sharedToOrgs: 'Shared to {count} space(s)', uninitializedBanner: 'Некоторые базы знаний не инициализированы. Сначала настройте модели в разделе настроек, чтобы добавлять документы.', - uploadProgress: { - uploadingTitle: 'Загрузка документов папки в «{name}»', - detail: 'Готово {completed} из {total} файлов', - keepPageOpen: 'Пожалуйста, не закрывайте страницу, пока идет загрузка.', - completedTitle: 'Загрузка для «{name}» завершена', - completedDetail: 'Загружено {total} файлов. Обновляем список, чтобы показать статус разбора...', - refreshing: 'Обновляем список и статусы разбора...', - errorTip: 'Часть файлов загрузить не удалось. Проверьте уведомления.', - unknownKb: 'База знаний {id}' - }, features: { knowledgeGraph: 'Граф знаний включен', multimodal: 'Мультимодальность включена', @@ -6733,13 +6772,6 @@ export default { tagLabel: 'Тег', tagPlaceholder: 'Выберите теги', noTags: 'Нет тегов', - uploadSuccess: 'Файл успешно загружен!', - uploadFailed: 'Ошибка загрузки файла!', - fileExists: 'Файл уже существует', - uploadAllSuccess: 'Успешно загружено {count} файлов!', - uploadPartialSuccess: 'Загрузка завершена: успешно {success}, ошибка {fail}', - uploadAllFailed: 'Все файлы не удалось загрузить', - uploadingFolder: 'Загрузка {total} файлов из папки...', videosFilteredNoVLM: 'Пропущено {count} видеофайлов (загрузка видео не поддерживается)', unsupportedTypesHint: 'Некоторые типы документов ({types}) не имеют доступного парсера и не могут быть обработаны', goToParserSettings: 'Настроить', @@ -6966,9 +6998,6 @@ export default { operationNotSupportedForType: 'Эта операция не поддерживается для текущего типа базы знаний', allFilesSkippedNoEngine: 'Все выбранные файлы были пропущены из-за отсутствия парсера', filesSkippedNoEngine: '{count} файл(ов) пропущено из-за отсутствия парсера', - allUploadSuccess: 'Все файлы загружены ({count})', - partialUploadSuccess: 'Частичная загрузка (успешно: {success}, ошибки: {fail})', - allUploadFailed: 'Все файлы не удалось загрузить ({count})', deleteSuccess: 'Знание удалено!', chunkLoadFailed: 'Не удалось загрузить фрагменты', infoCard: { diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 94e8fa11..80a69938 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -2608,6 +2608,55 @@ export default { onlineEdit: '在线编辑', deleteRecord: '删除记录' }, + uploadTasks: { + panelLabel: '上传任务', + titleUploading: '正在上传 {done}/{total}', + titleParsing: '正在解析 {done}/{total}', + titleDone: '全部完成', + titleDoneWithIssues: '{ok} 个完成,{bad} 个未成功', + titleCancelled: '上传已取消', + destination: '上传至「{name}」', + destinationMany: '上传至 {count} 个知识库', + remaining: '剩余约 {time}', + eta: { + seconds: '{n} 秒', + minutes: '{n} 分钟', + hours: '{n} 小时' + }, + hintUploading: '上传完成前请不要关闭或刷新页面', + hintParsing: '文件已全部上传,解析在后台继续,可以放心离开此页面', + legend: { + ready: '可检索', + active: '处理中', + waiting: '等待中', + failed: '失败', + duplicate: '已存在' + }, + filterAll: '全部', + filterIssues: '未成功', + phaseWaiting: '等待上传', + phaseSaving: '正在保存…', + phasePending: '排队解析', + phaseParsing: '解析中', + phaseFinalizing: '可检索,后台优化中', + phaseReady: '已完成', + phaseUploadFailed: '上传失败', + phaseParseFailed: '解析失败', + phaseDuplicate: '知识库中已有相同文件', + phaseCancelled: '已取消', + phaseDeleted: '已删除', + cancel: '取消', + cancelAll: '全部取消', + retry: '重试', + retryFailed: '重试 {count} 个', + open: '查看', + collapse: '收起', + expand: '展开', + close: '关闭', + closeConfirm: '关闭后将取消剩余 {count} 个文件的上传', + closeConfirmOk: '取消上传', + closeConfirmKeep: '继续上传' + }, time: { today: '今天', yesterday: '昨天', @@ -4731,16 +4780,6 @@ export default { subtitle: '管理和组织您的知识库,支持文档型和问答型知识库', sharedToOrgs: '已共享给 {count} 个空间', uninitializedBanner: '部分知识库尚未初始化,需要先在设置中配置模型信息才能添加知识文档', - uploadProgress: { - uploadingTitle: '正在向「{name}」上传文件夹中的文档', - detail: '已完成 {completed}/{total} 个文件', - keepPageOpen: '请保持页面打开,上传完成后会自动刷新解析状态。', - completedTitle: '「{name}」的上传已完成', - completedDetail: '共上传 {total} 个文件,正在刷新列表查看解析状态...', - refreshing: '正在刷新列表并获取最新解析状态...', - errorTip: '部分文件上传失败,请查看右上角通知详情。', - unknownKb: '知识库 {id}' - }, features: { knowledgeGraph: '知识图谱', multimodal: '多模态', @@ -6735,13 +6774,6 @@ export default { tagLabel: '标签', tagPlaceholder: '请选择标签', noTags: '暂无标签', - uploadSuccess: '已上传文件', - uploadFailed: '文件上传失败!', - fileExists: '文件已存在', - uploadAllSuccess: '成功上传 {count} 个文件!', - uploadPartialSuccess: '上传完成:成功 {success} 个,失败 {fail} 个', - uploadAllFailed: '所有文件上传失败', - uploadingFolder: '正在上传文件夹中的 {total} 个文件...', videosFilteredNoVLM: '已跳过 {count} 个视频文件(暂不支持视频上传)', unsupportedTypesHint: '部分文档类型({types})暂无可用解析引擎,上传后将无法解析', goToParserSettings: '前往配置', @@ -6968,9 +7000,6 @@ export default { operationNotSupportedForType: '当前知识库类型不支持该操作', allFilesSkippedNoEngine: '所选文件类型暂无可用解析引擎,已全部跳过', filesSkippedNoEngine: '{count} 个文件因无可用解析引擎被跳过', - allUploadSuccess: '所有文件上传成功({count}个)', - partialUploadSuccess: '部分文件上传成功(成功:{success},失败:{fail})', - allUploadFailed: '所有文件上传失败({count}个)', deleteSuccess: '已删除知识', chunkLoadFailed: '分块加载失败', infoCard: { diff --git a/frontend/src/stores/uploadQueue.test.ts b/frontend/src/stores/uploadQueue.test.ts new file mode 100644 index 00000000..54fba9c1 --- /dev/null +++ b/frontend/src/stores/uploadQueue.test.ts @@ -0,0 +1,281 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { + createListRefreshThrottle, + createUploadQueue, + type KnowledgeStatusRow, + type Timers, + type TransferEnd, + type UploadBatch, + type UploadPayload, + type UploadQueueDeps, +} from './uploadQueue.ts' +import type { UploadItem } from './uploadTasksState.ts' + +type Call = { + batch: UploadBatch + payload: UploadPayload + signal: AbortSignal + progress: (ratio: number) => void + resolve: (value: unknown) => void + reject: (reason: unknown) => void +} + +const file = (name: string, size = 100) => ({ name, size, webkitRelativePath: '' }) as unknown as File + +const flush = () => new Promise(resolve => setImmediate(resolve)) + +/** Timers that only fire when the test says so. */ +function manualTimers() { + const pending = new Set<{ fn: () => void; ms: number }>() + const timers: Timers = { + setTimer: (fn, ms) => { + const handle = { fn, ms } + pending.add(handle) + return handle + }, + clearTimer: handle => { + pending.delete(handle as { fn: () => void; ms: number }) + }, + } + const runAll = () => { + const due = [...pending] + pending.clear() + for (const handle of due) handle.fn() + } + return { timers, runAll, pending } +} + +function setup(overrides: Partial = {}) { + const items: UploadItem[] = [] + const batches: UploadBatch[] = [] + const calls: Call[] = [] + const ends: Array<[string, TransferEnd]> = [] + const statusRows = new Map() + const clock = manualTimers() + + const queue = createUploadQueue(items, batches, { + concurrency: 2, + pollIntervalMs: 1000, + pollChunkSize: 2, + upload: (batch, payload, progress, signal) => new Promise((resolve, reject) => { + calls.push({ batch, payload, signal, progress, resolve, reject }) + signal.addEventListener('abort', () => reject({ message: 'Network error' })) + }), + queryStatus: async (kbId, ids) => { + const rows = statusRows.get(kbId) + return rows === null ? null : (rows ?? []).filter(row => ids.includes(row.id)) + }, + onTransferEnd: (kbId, end) => ends.push([kbId, end]), + timers: clock.timers, + ...overrides, + }) + const batch = (kbId = 'kb1') => ({ kbId, kbName: 'KB', targetFolder: '' }) + const byName = (name: string) => items.find(item => item.name === name)! + return { items, batches, calls, ends, statusRows, clock, queue, batch, byName } +} + +test('runs at most `concurrency` transfers and starts the next as one settles', async () => { + const { calls, ends, queue, batch, byName } = setup() + queue.add(batch(), [{ file: file('a', 100) }, { file: file('b', 200) }, { file: file('c', 300) }]) + assert.deepEqual(calls.map(call => call.payload.file.name), ['a', 'b']) + assert.equal(byName('c').transfer, 'queued') + + calls[0].progress(0.4) + assert.equal(byName('a').loaded, 40) + + calls[0].resolve({ success: true, data: { id: 'k-a', parse_status: 'pending' } }) + await flush() + assert.equal(byName('a').transfer, 'uploaded') + assert.equal(byName('a').knowledgeId, 'k-a') + assert.deepEqual(calls.map(call => call.payload.file.name), ['a', 'b', 'c']) + assert.deepEqual(ends, [['kb1', { uploaded: true, settled: false }]]) +}) + +test('never runs two same-size files for one knowledge base at once', async () => { + const { calls, queue, batch } = setup({ concurrency: 3 }) + queue.add(batch(), [{ file: file('copy-1', 500) }, { file: file('copy-2', 500) }, { file: file('other', 7) }]) + queue.add(batch('kb2'), [{ file: file('elsewhere', 500) }]) + // copy-2 waits for copy-1, so the server's hash dedup sees copy-1's row. + assert.deepEqual(calls.map(call => call.payload.file.name), ['copy-1', 'other', 'elsewhere']) + + calls[0].resolve({ success: true, data: { id: 'k1' } }) + await flush() + assert.equal(calls[3].payload.file.name, 'copy-2') +}) + +test('classifies duplicates and failures, and retries a failed file', async () => { + const { calls, ends, queue, batch, byName } = setup() + queue.add(batch(), [{ file: file('dup', 1) }, { file: file('bad', 2) }]) + + calls[0].reject({ status: 409, code: 'duplicate_file', data: { id: 'k-old' } }) + calls[1].reject({ status: 400, message: 'too large' }) + await flush() + assert.equal(byName('dup').transfer, 'duplicate') + assert.equal(byName('dup').knowledgeId, 'k-old') + assert.equal(byName('bad').transfer, 'failed') + assert.equal(byName('bad').error, 'too large') + assert.deepEqual(ends.at(-1), ['kb1', { uploaded: false, settled: true }]) + + queue.retryFailed() + assert.equal(calls.length, 3) + assert.equal(calls[2].payload.file.name, 'bad') + // Duplicates are settled, not retryable. + assert.equal(byName('dup').transfer, 'duplicate') + calls[2].resolve({ success: true, data: { id: 'k-bad' } }) + await flush() + assert.equal(byName('bad').transfer, 'uploaded') + assert.equal(byName('bad').parseStatus, 'pending') + assert.deepEqual(ends.at(-1), ['kb1', { uploaded: true, settled: true }]) +}) + +test('cancelling aborts the request without reporting it as a failure', async () => { + const { calls, ends, queue, batch, byName } = setup() + queue.add(batch(), [{ file: file('a', 1) }, { file: file('b', 2) }, { file: file('c', 3) }]) + + queue.cancel(byName('c').id) + assert.equal(byName('c').transfer, 'cancelled') + + queue.cancel(byName('a').id) + assert.equal(calls[0].signal.aborted, true) + await flush() + assert.equal(byName('a').transfer, 'cancelled') + assert.equal(byName('a').error, undefined) + // The freed slot doesn't resurrect the cancelled queued file. + assert.equal(calls.length, 2) + assert.deepEqual(ends, [['kb1', { uploaded: false, settled: false }]]) + + // Fully sent: the server is already storing it, so it can't be cancelled. + calls[1].progress(1) + queue.cancel(byName('b').id) + assert.equal(calls[1].signal.aborted, false) + assert.equal(byName('b').transfer, 'uploading') +}) + +test('a late abort from a cancelled attempt cannot overwrite its retry', async () => { + let rejectFirst!: (reason: unknown) => void + const { calls, queue, batch, byName } = setup({ + // The first attempt ignores its signal, as a slow transport might. + upload: (b, payload, progress, signal) => new Promise((resolve, reject) => { + calls.push({ batch: b, payload, signal, progress, resolve, reject }) + if (calls.length === 1) rejectFirst = reject + }), + }) + queue.add(batch(), [{ file: file('a') }]) + queue.cancel(byName('a').id) + queue.retry(byName('a').id) + assert.equal(calls.length, 2) + + rejectFirst({ message: 'Network error' }) + await flush() + assert.equal(byName('a').transfer, 'uploading') + + calls[1].resolve({ success: true, data: { id: 'k-a' } }) + await flush() + assert.equal(byName('a').transfer, 'uploaded') +}) + +test('polls created rows until parsing settles', async () => { + const { calls, clock, statusRows, queue, batch, byName } = setup() + queue.add(batch(), [{ file: file('a', 1) }, { file: file('b', 2) }, { file: file('c', 3) }]) + calls[0].resolve({ success: true, data: { id: 'k-a', parse_status: 'pending' } }) + calls[1].resolve({ success: true, data: { id: 'k-b', parse_status: 'pending' } }) + await flush() + calls[2].resolve({ success: true, data: { id: 'k-c', parse_status: 'pending' } }) + await flush() + // One timer no matter how many uploads landed. + assert.equal(clock.pending.size, 1) + + statusRows.set('kb1', null) + await queue.pollNow() + assert.equal(byName('a').parseStatus, 'pending', 'a failed request changes nothing') + + statusRows.set('kb1', [ + { id: 'k-a', parse_status: 'completed' }, + { id: 'k-b', parse_status: 'failed', error_message: 'broken pdf' }, + ]) + await queue.pollNow() + assert.equal(byName('a').parseStatus, 'completed') + assert.equal(byName('b').parseStatus, 'failed') + assert.equal(byName('b').parseError, 'broken pdf') + // Missing from one answer is not proof of deletion. + assert.equal(byName('c').parseStatus, 'pending') + await queue.pollNow() + assert.equal(byName('c').parseStatus, 'pending') + await queue.pollNow() + assert.equal(byName('c').parseStatus, 'deleted') +}) + +test('a row that reappears resets its missing count', async () => { + const { calls, statusRows, queue, batch, byName } = setup() + queue.add(batch(), [{ file: file('a') }]) + calls[0].resolve({ success: true, data: { id: 'k-a', parse_status: 'pending' } }) + await flush() + + statusRows.set('kb1', []) + await queue.pollNow() + await queue.pollNow() + statusRows.set('kb1', [{ id: 'k-a', parse_status: 'processing' }]) + await queue.pollNow() + statusRows.set('kb1', []) + await queue.pollNow() + await queue.pollNow() + assert.equal(byName('a').parseStatus, 'processing') +}) + +test('clear() lets fully sent files finish and reports them, but aborts the rest', async () => { + const { items, batches, calls, ends, queue, batch } = setup() + queue.add(batch(), [{ file: file('sent', 1) }, { file: file('sending', 2) }]) + calls[0].progress(1) + calls[1].progress(0.3) + + queue.clear() + assert.equal(calls[0].signal.aborted, false) + assert.equal(calls[1].signal.aborted, true) + assert.equal(items.length, 0) + assert.equal(batches.length, 0) + assert.deepEqual(ends, [['kb1', { uploaded: false, settled: true }]]) + + queue.add(batch(), [{ file: file('next', 3) }]) + calls[0].resolve({ success: true, data: { id: 'late' } }) + await flush() + assert.deepEqual(items.map(item => item.name), ['next']) + // The late file is new in the list; the new batch still has work queued. + assert.deepEqual(ends.at(-1), ['kb1', { uploaded: true, settled: false }]) +}) + +test('pruneFinished drops clean batches and keeps ones with issues', async () => { + const { items, batches, calls, statusRows, queue, batch } = setup() + queue.add(batch(), [{ file: file('ok', 1) }]) + queue.add(batch(), [{ file: file('broken', 2) }]) + calls[0].resolve({ success: true, data: { id: 'k-ok' } }) + calls[1].reject({ status: 500, message: 'boom' }) + await flush() + statusRows.set('kb1', [{ id: 'k-ok', parse_status: 'completed' }]) + await queue.pollNow() + + queue.pruneFinished() + assert.equal(batches.length, 1) + assert.deepEqual(items.map(item => item.name), ['broken']) +}) + +test('list refresh throttle: mid-batch at most once per interval, one final refresh', () => { + const emitted: Array<[string, boolean]> = [] + const clock = manualTimers() + const notify = createListRefreshThrottle((kbId, settled) => emitted.push([kbId, settled]), 2000, 150, clock.timers) + + notify('kb1', { uploaded: true, settled: false }) + notify('kb1', { uploaded: true, settled: false }) + notify('kb1', { uploaded: false, settled: false }) + assert.deepEqual(emitted, [['kb1', false]]) + clock.runAll() + assert.deepEqual(emitted, [['kb1', false], ['kb1', false]]) + + // Several ends settling together (cancel all) make one final refresh. + notify('kb1', { uploaded: false, settled: true }) + notify('kb1', { uploaded: false, settled: true }) + clock.runAll() + assert.deepEqual(emitted.slice(2), [['kb1', true]]) + clock.runAll() + assert.equal(emitted.length, 3) +}) diff --git a/frontend/src/stores/uploadQueue.ts b/frontend/src/stores/uploadQueue.ts new file mode 100644 index 00000000..b1eba43e --- /dev/null +++ b/frontend/src/stores/uploadQueue.ts @@ -0,0 +1,369 @@ +import type { KnowledgeProcessOverrides } from '@/types/knowledgeProcess' +import { + classifyUploadResult, + itemPhase, + needsParsePolling, + pickNextToStart, + type UploadItem, +} from './uploadTasksState' + +/** + * The upload queue's behaviour — bounded concurrent transfers, cancel, retry + * and polling the created rows until parsing settles — with the network and + * timers injected, so the store only wires it to the API and Vue. + * + * `items` and `batches` are mutated in place (never reassigned) so a reactive + * array handed in by the store stays the one the panel renders. + */ + +export interface UploadBatch { + id: string + kbId: string + kbName: string + /** Destination folder, '' for the knowledge base root. */ + targetFolder: string + tagIds?: string[] + processConfig?: KnowledgeProcessOverrides +} + +export interface UploadPayload { + file: File + /** Path-qualified name the backend splits into folder + file name. */ + fileName?: string +} + +export interface KnowledgeStatusRow { + id: string + parse_status?: string + error_message?: string +} + +export interface TransferEnd { + /** The file reached the server, so the knowledge base has a new row. */ + uploaded: boolean + /** Nothing is queued or uploading for this knowledge base any more. */ + settled: boolean +} + +export interface Timers { + setTimer: (fn: () => void, ms: number) => unknown + clearTimer: (handle: unknown) => void +} + +export const defaultTimers: Timers = { + setTimer: (fn, ms) => setTimeout(fn, ms), + clearTimer: handle => clearTimeout(handle as ReturnType), +} + +export interface UploadQueueDeps { + concurrency: number + pollIntervalMs: number + /** Most knowledge ids asked about in one status request. */ + pollChunkSize: number + /** Resolves or rejects with the API's response body; the queue classifies either. */ + upload: ( + batch: UploadBatch, + payload: UploadPayload, + onProgress: (ratio: number) => void, + signal: AbortSignal, + ) => Promise + /** Current rows for the ids, or null when the request failed. */ + queryStatus: (kbId: string, knowledgeIds: string[]) => Promise + /** Called whenever a transfer ends, including one that outlived clear(). */ + onTransferEnd: (kbId: string, end: TransferEnd) => void + timers?: Timers +} + +/** + * Consecutive successful polls a row must be missing from before it counts as + * deleted, so one odd answer can't strand a live document as "Deleted". + */ +const MISSING_POLLS_BEFORE_DELETED = 3 + +let idSeq = 0 +const nextId = (prefix: string) => `${prefix}-${Date.now().toString(36)}-${(idSeq++).toString(36)}` + +export function createUploadQueue(items: UploadItem[], batches: UploadBatch[], deps: UploadQueueDeps) { + const { setTimer, clearTimer } = deps.timers ?? defaultTimers + + // File payloads and abort handles stay out of the (possibly reactive) items: + // proxying a File buys nothing and the panel never renders them. + const payloads = new Map() + const controllers = new Map() + const missingPolls = new Map() + // Bumped by clear(), so work started before it cannot touch what comes after. + let generation = 0 + let pollTimer: unknown = null + + const batchOf = (item: UploadItem) => batches.find(batch => batch.id === item.batchId) + const findItem = (id: string) => items.find(item => item.id === id) + + const isBusy = (kbId: string) => items.some(item => + (item.transfer === 'queued' || item.transfer === 'uploading') && batchOf(item)?.kbId === kbId) + + // ---- transfer ----------------------------------------------------------- + + // Identical files always have the same size. Keeping same-size files for one + // knowledge base out of flight together lets the server's content-hash dedup, + // which only sees rows already written, catch the second copy. + const dedupKey = (item: UploadItem) => `${batchOf(item)?.kbId}:${item.size}` + + const pump = () => { + for (const item of pickNextToStart(items, deps.concurrency, dedupKey)) void transfer(item) + } + + const transfer = async (item: UploadItem) => { + const batch = batchOf(item) + const payload = payloads.get(item.id) + if (!batch || !payload) { + item.transfer = 'failed' + return + } + const startedIn = generation + const controller = new AbortController() + controllers.set(item.id, controller) + item.transfer = 'uploading' + item.loaded = 0 + item.error = undefined + + let result: unknown + try { + result = await deps.upload(batch, payload, ratio => { + if (item.transfer === 'uploading') item.loaded = Math.min(item.size, Math.round(ratio * item.size)) + }, controller.signal) + } catch (error) { + result = error + } + // A retry after a cancel starts a new attempt under the same id; only the + // latest attempt may write the item. + const latestAttempt = controllers.get(item.id) === controller + if (latestAttempt) controllers.delete(item.id) + const aborted = controller.signal.aborted + + // Outlived clear(): the row is gone from the panel, but a file that still + // made it (clear() lets fully sent files finish) is new in the list. + if (startedIn !== generation) { + if (!aborted && classifyUploadResult(result).kind === 'uploaded') { + deps.onTransferEnd(batch.kbId, { uploaded: true, settled: !isBusy(batch.kbId) }) + } + return + } + if (!latestAttempt) return + + if (aborted || item.transfer !== 'uploading') { + // Cancelled mid-flight; the abort rejection carries nothing worth showing. + if (item.transfer === 'uploading') item.transfer = 'cancelled' + } else { + const outcome = classifyUploadResult(result) + if (outcome.kind === 'uploaded') { + item.transfer = 'uploaded' + item.loaded = item.size + item.knowledgeId = outcome.knowledgeId + item.parseStatus = outcome.parseStatus || 'pending' + payloads.delete(item.id) + schedulePoll() + } else if (outcome.kind === 'duplicate') { + item.transfer = 'duplicate' + item.knowledgeId = outcome.knowledgeId + payloads.delete(item.id) + } else { + item.transfer = 'failed' + item.error = outcome.message + } + } + deps.onTransferEnd(batch.kbId, { uploaded: item.transfer === 'uploaded', settled: !isBusy(batch.kbId) }) + pump() + } + + const add = (batchInput: Omit, uploads: UploadPayload[]) => { + const batch: UploadBatch = { ...batchInput, id: nextId('batch') } + batches.push(batch) + for (const upload of uploads) { + const id = nextId('upload') + payloads.set(id, upload) + items.push({ + id, + batchId: batch.id, + name: upload.file.name, + relativePath: upload.file.webkitRelativePath || '', + size: upload.file.size, + loaded: 0, + transfer: 'queued', + }) + } + pump() + return batch + } + + const cancel = (id: string) => { + const item = findItem(id) + if (!item || (item.transfer !== 'queued' && item.transfer !== 'uploading')) return + // Once the whole body is sent the server is already storing the file; + // aborting now would hide a row that still gets created. + if (itemPhase(item) === 'saving') return + item.transfer = 'cancelled' + item.loaded = 0 + const controller = controllers.get(id) + if (controller) { + // Its transfer reports the end once the abort lands. + controller.abort() + return + } + const kbId = batchOf(item)?.kbId + if (kbId && !isBusy(kbId)) deps.onTransferEnd(kbId, { uploaded: false, settled: true }) + } + + const cancelAll = () => { + for (const item of items) cancel(item.id) + } + + const retry = (id: string) => { + const item = findItem(id) + if (!item || (item.transfer !== 'failed' && item.transfer !== 'cancelled') || !payloads.has(id)) return + item.transfer = 'queued' + item.loaded = 0 + item.error = undefined + pump() + } + + const retryFailed = () => { + for (const item of items) retry(item.id) + } + + /** Drop batches whose every file is searchable; anything with an issue stays. */ + const pruneFinished = () => { + for (const batch of [...batches]) { + const own = items.filter(item => item.batchId === batch.id) + if (!own.every(item => itemPhase(item) === 'ready')) continue + for (const item of own) { + items.splice(items.indexOf(item), 1) + missingPolls.delete(item.id) + } + batches.splice(batches.indexOf(batch), 1) + } + } + + // ---- parse polling ------------------------------------------------------ + + function schedulePoll() { + if (pollTimer !== null || !items.some(needsParsePolling)) return + pollTimer = setTimer(() => { + pollTimer = null + void pollNow() + }, deps.pollIntervalMs) + } + + const pollNow = async () => { + const startedIn = generation + const byKb = new Map() + for (const item of items) { + const kbId = needsParsePolling(item) ? batchOf(item)?.kbId : undefined + if (!kbId) continue + if (!byKb.has(kbId)) byKb.set(kbId, []) + byKb.get(kbId)!.push(item) + } + + const requests: Promise[] = [] + for (const [kbId, group] of byKb) { + for (let i = 0; i < group.length; i += deps.pollChunkSize) { + const chunk = group.slice(i, i + deps.pollChunkSize) + requests.push(deps.queryStatus(kbId, chunk.map(item => item.knowledgeId!)).then(rows => { + // A failed request just waits for the next tick. + if (!rows || startedIn !== generation) return + const byId = new Map(rows.map(row => [row.id, row])) + for (const item of chunk) { + const row = byId.get(item.knowledgeId!) + if (!row) { + const misses = (missingPolls.get(item.id) ?? 0) + 1 + missingPolls.set(item.id, misses) + if (misses >= MISSING_POLLS_BEFORE_DELETED) item.parseStatus = 'deleted' + continue + } + missingPolls.delete(item.id) + item.parseStatus = row.parse_status + item.parseError = row.error_message || undefined + } + }, () => {})) + } + } + await Promise.all(requests) + if (startedIn === generation) schedulePoll() + } + + // ---- lifecycle ---------------------------------------------------------- + + /** + * Forget everything. Transfers still sending are aborted; ones whose body is + * fully sent are left to finish, since the server stores them regardless. + */ + const clear = () => { + generation++ + for (const item of items) { + if (itemPhase(item) !== 'saving') controllers.get(item.id)?.abort() + } + const busyKbs = new Set(items.filter(item => item.transfer === 'queued' || item.transfer === 'uploading') + .map(item => batchOf(item)?.kbId) + .filter((kbId): kbId is string => !!kbId)) + controllers.clear() + payloads.clear() + missingPolls.clear() + items.splice(0) + batches.splice(0) + if (pollTimer !== null) { + clearTimer(pollTimer) + pollTimer = null + } + // Files that landed before the clear may still be waiting for a refresh. + for (const kbId of busyKbs) deps.onTransferEnd(kbId, { uploaded: false, settled: true }) + } + + return { add, cancel, cancelAll, retry, retryFailed, pruneFinished, pollNow, clear } +} + +/** + * Turns transfer ends into `knowledgeFileUploaded` refreshes: while a knowledge + * base still has work queued, at most one mid-batch (`settled: false`) refresh + * per `intervalMs`; once it settles, a single final (`settled: true`) one. + * Ends that settle within `coalesceMs` of each other (cancel-all aborting + * several requests) produce one final refresh. + */ +export function createListRefreshThrottle( + emit: (kbId: string, settled: boolean) => void, + intervalMs: number, + coalesceMs: number, + timers: Timers = defaultTimers, +) { + const throttles = new Map() + const pending = new Set() + const finals = new Map() + + return (kbId: string, end: TransferEnd) => { + if (end.settled) { + const throttle = throttles.get(kbId) + if (throttle !== undefined) timers.clearTimer(throttle) + throttles.delete(kbId) + pending.delete(kbId) + if (finals.has(kbId)) return + finals.set(kbId, timers.setTimer(() => { + finals.delete(kbId) + emit(kbId, true) + }, coalesceMs)) + return + } + if (!end.uploaded) return + if (throttles.has(kbId)) { + pending.add(kbId) + return + } + emit(kbId, false) + const tick = () => { + if (pending.delete(kbId)) { + emit(kbId, false) + throttles.set(kbId, timers.setTimer(tick, intervalMs)) + } else { + throttles.delete(kbId) + } + } + throttles.set(kbId, timers.setTimer(tick, intervalMs)) + } +} diff --git a/frontend/src/stores/uploadTasks.ts b/frontend/src/stores/uploadTasks.ts new file mode 100644 index 00000000..aeb1d6a2 --- /dev/null +++ b/frontend/src/stores/uploadTasks.ts @@ -0,0 +1,48 @@ +import { defineStore } from 'pinia' +import { batchQueryKnowledge, uploadKnowledgeFile } from '@/api/knowledge-base/index' +import { useAuthStore } from './auth' +import type { KnowledgeStatusRow } from './uploadQueue' +import { createUploadTasks } from './uploadTasksCore' + +export type { UploadBatch } from './uploadQueue' +export type { EnqueueUploadsInput } from './uploadTasksCore' + +/** + * Knowledge file uploads behind the floating progress panel + * (components/upload-tasks/UploadTasksPanel.vue). Lives in a store rather than + * the knowledge base page so uploads keep going, and stay visible, when the + * user navigates elsewhere in the app. Behaviour is in uploadTasksCore.ts and + * uploadQueue.ts; this file only connects it to the API and the page. + */ +export const useUploadTasksStore = defineStore('uploadTasks', () => { + const auth = useAuthStore() + + return createUploadTasks({ + upload: (batch, payload, onProgress, signal) => uploadKnowledgeFile( + batch.kbId, + { + file: payload.file, + fileName: payload.fileName, + tag_ids: batch.tagIds, + process_config: batch.processConfig, + }, + (event: { loaded?: number; total?: number; progress?: number }) => { + onProgress(event.progress ?? (event.total ? (event.loaded ?? 0) / event.total : 0)) + }, + { signal }, + ), + queryStatus: async (kbId, knowledgeIds) => { + const query = knowledgeIds.map(id => `ids=${encodeURIComponent(id)}`).join('&') + try { + const result: any = await batchQueryKnowledge(query, kbId) + return result?.success && Array.isArray(result.data) ? (result.data as KnowledgeStatusRow[]) : null + } catch { + return null + } + }, + emitListRefresh: (kbId, settled) => { + window.dispatchEvent(new CustomEvent('knowledgeFileUploaded', { detail: { kbId, settled } })) + }, + owner: [() => auth.user?.id, () => auth.effectiveTenantId], + }) +}) diff --git a/frontend/src/stores/uploadTasksCore.test.ts b/frontend/src/stores/uploadTasksCore.test.ts new file mode 100644 index 00000000..126d874c --- /dev/null +++ b/frontend/src/stores/uploadTasksCore.test.ts @@ -0,0 +1,69 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { ref } from 'vue' +import type { Timers, UploadBatch, UploadPayload } from './uploadQueue.ts' +import { createUploadTasks } from './uploadTasksCore.ts' + +type Call = { batch: UploadBatch; payload: UploadPayload; signal: AbortSignal; resolve: (v: unknown) => void; reject: (r: unknown) => void } + +const file = (name: string, size = 100) => ({ name, size, webkitRelativePath: '' }) as unknown as File +const flush = () => new Promise(resolve => setImmediate(resolve)) +const noTimers: Timers = { setTimer: () => ({}), clearTimer: () => {} } + +function setup() { + const user = ref<{ id: string; nickname?: string } | null>({ id: 'u1' }) + const tenant = ref(1) + const calls: Call[] = [] + const tasks = createUploadTasks({ + upload: (batch, payload, _progress, signal) => new Promise((resolve, reject) => { + calls.push({ batch, payload, signal, resolve, reject }) + signal.addEventListener('abort', () => reject({ message: 'Network error' })) + }), + queryStatus: async () => [], + emitListRefresh: () => {}, + owner: [() => user.value?.id, () => tenant.value], + timers: noTimers, + }) + const enqueue = (name: string, size = 100) => + tasks.enqueue({ kbId: 'kb1', kbName: 'KB', uploads: [{ file: file(name, size) }] }) + return { user, tenant, calls, tasks, enqueue } +} + +test('replacing the user object for the same person keeps uploads running', () => { + const { user, tenant, calls, tasks, enqueue } = setup() + enqueue('a') + // What setUser() does on every /auth/me refresh. + user.value = { id: 'u1', nickname: 'refreshed' } + assert.equal(tasks.items.length, 1) + assert.equal(calls[0].signal.aborted, false) + assert.equal(tasks.visible.value, true) + + tenant.value = 2 + assert.equal(tasks.items.length, 0) + assert.equal(calls[0].signal.aborted, true) + assert.equal(tasks.visible.value, false) +}) + +test('a new batch keeps an earlier batch that still has failures to retry', async () => { + const { calls, tasks, enqueue } = setup() + enqueue('broken', 1) + calls[0].reject({ status: 500, message: 'boom' }) + await flush() + assert.equal(tasks.summary.value.stage, 'done') + + enqueue('next', 2) + assert.deepEqual(tasks.items.map(item => item.name), ['broken', 'next']) + tasks.retryItem(tasks.items[0].id) + assert.equal(calls.at(-1)!.payload.file.name, 'broken') +}) + +test('a new batch drops earlier batches that finished cleanly', async () => { + const { calls, tasks, enqueue } = setup() + enqueue('done', 1) + calls[0].resolve({ success: true, data: { id: 'k1', parse_status: 'completed' } }) + await flush() + + enqueue('next', 2) + assert.deepEqual(tasks.items.map(item => item.name), ['next']) + assert.equal(tasks.batches.length, 1) +}) diff --git a/frontend/src/stores/uploadTasksCore.ts b/frontend/src/stores/uploadTasksCore.ts new file mode 100644 index 00000000..365f0090 --- /dev/null +++ b/frontend/src/stores/uploadTasksCore.ts @@ -0,0 +1,125 @@ +import { computed, reactive, ref, watch, type WatchSource } from 'vue' +import type { KnowledgeProcessOverrides } from '@/types/knowledgeProcess' +import { + createListRefreshThrottle, + createUploadQueue, + defaultTimers, + type Timers, + type UploadBatch, + type UploadPayload, + type UploadQueueDeps, +} from './uploadQueue' +import { summarizeItems, type UploadItem } from './uploadTasksState' + +/** + * Everything the uploadTasks store does, with the API, page events and the + * signed-in identity injected so it runs (and is tested) without the app. + */ + +/** + * Parallel transfers. The server hashes and stores every file before it + * answers, so a small number keeps the pipe full without piling work on it. + */ +const CONCURRENCY = 3 +const POLL_INTERVAL_MS = 3000 +/** Keeps the ids=… query string of one status request well under URL length limits. */ +const POLL_CHUNK_SIZE = 40 +/** Minimum gap between mid-batch list refreshes pushed to an open page. */ +const LIST_REFRESH_INTERVAL_MS = 2000 +/** Batch ends this close together produce one final refresh. */ +const LIST_REFRESH_COALESCE_MS = 150 + +export interface EnqueueUploadsInput { + kbId: string + kbName: string + targetFolder?: string + tagIds?: string[] + processConfig?: KnowledgeProcessOverrides + uploads: UploadPayload[] +} + +export interface UploadTasksDeps { + upload: UploadQueueDeps['upload'] + queryStatus: UploadQueueDeps['queryStatus'] + /** Ask an open knowledge base page or list to reload; `settled` marks a batch's last one. */ + emitListRefresh: (kbId: string, settled: boolean) => void + /** + * Who the uploads belong to, as getters of primitive ids. Changing any of + * them drops the queue. + */ + owner: WatchSource[] + timers?: Timers +} + +export function createUploadTasks(deps: UploadTasksDeps) { + const items = reactive([]) + const batches = reactive([]) + const visible = ref(false) + const collapsed = ref(false) + const timers = deps.timers ?? defaultTimers + + const summary = computed(() => summarizeItems(items)) + const batchById = computed(() => new Map(batches.map(batch => [batch.id, batch]))) + + const queue = createUploadQueue(items, batches, { + concurrency: CONCURRENCY, + pollIntervalMs: POLL_INTERVAL_MS, + pollChunkSize: POLL_CHUNK_SIZE, + upload: deps.upload, + queryStatus: deps.queryStatus, + onTransferEnd: createListRefreshThrottle( + deps.emitListRefresh, + LIST_REFRESH_INTERVAL_MS, + LIST_REFRESH_COALESCE_MS, + timers, + ), + timers, + }) + + const enqueue = (input: EnqueueUploadsInput) => { + if (!input.kbId || input.uploads.length === 0) return + // Batches that finished cleanly have nothing left to show; ones with + // failures stay so their files can still be retried. + queue.pruneFinished() + queue.add({ + kbId: input.kbId, + kbName: input.kbName, + targetFolder: input.targetFolder || '', + tagIds: input.tagIds && input.tagIds.length > 0 ? [...input.tagIds] : undefined, + processConfig: input.processConfig, + }, input.uploads) + visible.value = true + collapsed.value = false + } + + /** Hide the panel and forget every task, cancelling transfers still sending. */ + const dismiss = () => { + queue.clear() + visible.value = false + } + + const toggleCollapsed = () => { + collapsed.value = !collapsed.value + } + + // Uploads belong to the account and space they were started in. The ids are + // separate watch sources on purpose: one getter returning a fresh array would + // fire on every setUser(), even for the same person, and kill running uploads. + watch(deps.owner, dismiss, { flush: 'sync' }) + + return { + items, + batches, + visible, + collapsed, + summary, + batchById, + enqueue, + cancelItem: queue.cancel, + cancelAll: queue.cancelAll, + retryItem: queue.retry, + retryFailed: queue.retryFailed, + dismiss, + toggleCollapsed, + } +} diff --git a/frontend/src/stores/uploadTasksState.test.ts b/frontend/src/stores/uploadTasksState.test.ts new file mode 100644 index 00000000..c6df252d --- /dev/null +++ b/frontend/src/stores/uploadTasksState.test.ts @@ -0,0 +1,163 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { + classifyUploadResult, + estimateRate, + estimateRemainingSeconds, + itemPhase, + needsParsePolling, + pickNextToStart, + splitDuration, + summarizeItems, + type UploadItem, +} from './uploadTasksState.ts' + +let seq = 0 +const item = (patch: Partial = {}): UploadItem => ({ + id: `item-${seq++}`, + batchId: 'batch', + name: 'a.pdf', + relativePath: '', + size: 100, + loaded: 0, + transfer: 'queued', + ...patch, +}) + +test('itemPhase folds transfer and parse state into one row status', () => { + assert.equal(itemPhase(item()), 'waiting') + assert.equal(itemPhase(item({ transfer: 'uploading', loaded: 40 })), 'uploading') + assert.equal(itemPhase(item({ transfer: 'uploading', loaded: 100 })), 'saving') + assert.equal(itemPhase(item({ transfer: 'uploaded', parseStatus: 'pending' })), 'parsing') + assert.equal(itemPhase(item({ transfer: 'uploaded', parseStatus: 'processing' })), 'parsing') + // finalizing is already searchable, so it counts as ready. + assert.equal(itemPhase(item({ transfer: 'uploaded', parseStatus: 'finalizing' })), 'ready') + assert.equal(itemPhase(item({ transfer: 'uploaded', parseStatus: 'completed' })), 'ready') + assert.equal(itemPhase(item({ transfer: 'uploaded', parseStatus: 'failed' })), 'failed') + assert.equal(itemPhase(item({ transfer: 'uploaded', parseStatus: 'deleted' })), 'cancelled') + assert.equal(itemPhase(item({ transfer: 'failed' })), 'failed') + assert.equal(itemPhase(item({ transfer: 'duplicate' })), 'duplicate') + assert.equal(itemPhase(item({ transfer: 'cancelled' })), 'cancelled') +}) + +test('needsParsePolling keeps watching until the row leaves finalizing', () => { + assert.equal(needsParsePolling(item({ transfer: 'uploaded', knowledgeId: 'k', parseStatus: 'pending' })), true) + assert.equal(needsParsePolling(item({ transfer: 'uploaded', knowledgeId: 'k', parseStatus: 'finalizing' })), true) + assert.equal(needsParsePolling(item({ transfer: 'uploaded', knowledgeId: 'k', parseStatus: 'completed' })), false) + assert.equal(needsParsePolling(item({ transfer: 'uploaded', parseStatus: 'pending' })), false) + assert.equal(needsParsePolling(item({ transfer: 'duplicate', knowledgeId: 'k' })), false) +}) + +test('summarizeItems reports the uploading stage while anything is queued or in flight', () => { + const summary = summarizeItems([ + item({ transfer: 'uploaded', parseStatus: 'completed' }), + item({ transfer: 'uploading', loaded: 50 }), + item(), + item({ transfer: 'failed' }), + ]) + assert.equal(summary.stage, 'uploading') + assert.equal(summary.transferSettled, 2) + assert.equal(summary.transferTotal, 4) + assert.equal(summary.loadedBytes, 250) + // The failed file is settled for the remaining-bytes estimate but never counts as sent. + assert.equal(summary.sentBytes, 150) + assert.equal(summary.totalBytes, 400) + assert.equal(summary.retryable, 1) + assert.deepEqual(summary.bar, { ready: 0.25, active: 0.125, failed: 0.25, duplicate: 0 }) +}) + +test('summarizeItems moves to parsing once every transfer settled, then to done', () => { + const parsing = summarizeItems([ + item({ transfer: 'uploaded', parseStatus: 'processing' }), + item({ transfer: 'uploaded', parseStatus: 'finalizing' }), + item({ transfer: 'duplicate' }), + ]) + assert.equal(parsing.stage, 'parsing') + assert.equal(parsing.uploaded, 2) + assert.equal(parsing.parsing, 1) + assert.equal(parsing.ready, 1) + + const done = summarizeItems([ + item({ transfer: 'uploaded', parseStatus: 'completed' }), + item({ transfer: 'uploaded', parseStatus: 'failed' }), + ]) + assert.equal(done.stage, 'done') + assert.equal(done.failed, 1) + // A parse failure cannot be retried by uploading again. + assert.equal(done.retryable, 0) +}) + +test('cancelled transfers leave the bar denominator and byte totals', () => { + const summary = summarizeItems([ + item({ transfer: 'uploaded', parseStatus: 'completed' }), + item({ transfer: 'cancelled' }), + ]) + assert.equal(summary.stage, 'done') + assert.equal(summary.transferTotal, 1) + assert.equal(summary.totalBytes, 100) + assert.equal(summary.retryable, 1) + assert.equal(summary.bar.ready, 1) +}) + +test('pickNextToStart fills free slots in queue order', () => { + const items = [ + item({ transfer: 'uploading' }), + item({ transfer: 'uploaded' }), + item({ id: 'q1' }), + item({ id: 'q2' }), + item({ id: 'q3' }), + ] + assert.deepEqual(pickNextToStart(items, 3).map(i => i.id), ['q1', 'q2']) + assert.deepEqual(pickNextToStart(items, 1), []) +}) + +test('pickNextToStart skips items whose conflict key is already in flight', () => { + const items = [ + item({ transfer: 'uploading', size: 10 }), + item({ id: 'same-as-running', size: 10 }), + item({ id: 'first-of-pair', size: 20 }), + item({ id: 'second-of-pair', size: 20 }), + item({ id: 'free', size: 30 }), + ] + const bySize = (i: UploadItem) => String(i.size) + assert.deepEqual(pickNextToStart(items, 3, bySize).map(i => i.id), ['first-of-pair', 'free']) +}) + +test('classifyUploadResult reads success, duplicate rejections and failures', () => { + assert.deepEqual( + classifyUploadResult({ success: true, data: { id: 'k1', parse_status: 'pending' } }), + { kind: 'uploaded', knowledgeId: 'k1', parseStatus: 'pending' }, + ) + assert.deepEqual( + classifyUploadResult({ status: 409, success: false, code: 'duplicate_file', message: 'exists', data: { id: 'k0' } }), + { kind: 'duplicate', knowledgeId: 'k0', message: 'exists' }, + ) + assert.deepEqual( + classifyUploadResult({ status: 400, success: false, error: { code: 'bad', message: 'too large' } }), + { kind: 'failed', message: 'too large' }, + ) + assert.deepEqual(classifyUploadResult({ message: 'Network error' }), { kind: 'failed', message: 'Network error' }) + assert.deepEqual(classifyUploadResult(undefined), { kind: 'failed', message: undefined }) +}) + +test('estimateRate waits for a one second window and ignores stale samples', () => { + assert.equal(estimateRate([{ at: 0, bytes: 0 }, { at: 500, bytes: 1000 }]), 0) + assert.equal(estimateRate([{ at: 0, bytes: 0 }, { at: 2000, bytes: 4000 }]), 2000) + const samples = [ + { at: 0, bytes: 0 }, + { at: 10_000, bytes: 100_000 }, + { at: 12_000, bytes: 104_000 }, + ] + assert.equal(estimateRate(samples, 8000), 2000) +}) + +test('remaining time is rounded into a stable unit', () => { + assert.equal(estimateRemainingSeconds(1000, 0), null) + assert.equal(estimateRemainingSeconds(0, 100), null) + assert.equal(estimateRemainingSeconds(1000, 300), 4) + assert.deepEqual(splitDuration(4), { unit: 'seconds', value: 5 }) + assert.deepEqual(splitDuration(41), { unit: 'seconds', value: 45 }) + assert.deepEqual(splitDuration(57), { unit: 'minutes', value: 1 }) + assert.deepEqual(splitDuration(610), { unit: 'minutes', value: 11 }) + assert.deepEqual(splitDuration(5400), { unit: 'hours', value: 1.5 }) +}) diff --git a/frontend/src/stores/uploadTasksState.ts b/frontend/src/stores/uploadTasksState.ts new file mode 100644 index 00000000..7499d989 --- /dev/null +++ b/frontend/src/stores/uploadTasksState.ts @@ -0,0 +1,271 @@ +/** + * Framework-free rules behind the knowledge upload queue (stores/uploadTasks.ts): + * how an item's transfer and parse states fold into one display phase, how a + * set of items summarises into the panel header, and which queued items may + * start next. Kept pure so the store stays a thin reactive shell over them. + */ + +/** Client-side life of one file's HTTP upload. */ +export type TransferStatus = 'queued' | 'uploading' | 'uploaded' | 'failed' | 'duplicate' | 'cancelled' + +export interface UploadItem { + id: string + batchId: string + name: string + /** webkitRelativePath for folder uploads, '' otherwise. */ + relativePath: string + size: number + /** Bytes of the file body sent so far, scaled from the multipart progress. */ + loaded: number + transfer: TransferStatus + /** Transfer failure reason. */ + error?: string + /** Knowledge created by this upload, or the existing one for a duplicate. */ + knowledgeId?: string + /** Backend parse_status once uploaded; 'deleted' when the row disappeared. */ + parseStatus?: string + parseError?: string +} + +/** + * One status per row, combining both stages. `saving` is the gap between the + * last request byte leaving the browser and the response arriving, while the + * server hashes and stores the file. + */ +export type ItemPhase = + | 'waiting' + | 'uploading' + | 'saving' + | 'parsing' + | 'ready' + | 'failed' + | 'duplicate' + | 'cancelled' + +export type UploadStage = 'uploading' | 'parsing' | 'done' + +export function itemPhase(item: UploadItem): ItemPhase { + switch (item.transfer) { + case 'queued': + return 'waiting' + case 'uploading': + return item.size > 0 && item.loaded >= item.size ? 'saving' : 'uploading' + case 'failed': + return 'failed' + case 'duplicate': + return 'duplicate' + case 'cancelled': + return 'cancelled' + } + switch (item.parseStatus) { + // finalizing means the document is already searchable; summary / question / + // graph enrichment keeps running in the background. + case 'finalizing': + case 'completed': + return 'ready' + case 'failed': + return 'failed' + case 'cancelled': + case 'deleting': + case 'deleted': + return 'cancelled' + default: + return 'parsing' + } +} + +/** Parse states the panel keeps polling. finalizing is polled so the row can settle on completed. */ +export function needsParsePolling(item: UploadItem): boolean { + if (item.transfer !== 'uploaded' || !item.knowledgeId) return false + const status = item.parseStatus + return !status || status === 'pending' || status === 'processing' || status === 'finalizing' +} + +export interface UploadSummary { + total: number + waiting: number + /** Includes `saving`. */ + uploading: number + parsing: number + ready: number + failed: number + duplicate: number + cancelled: number + /** Items whose transfer settled (uploaded, failed or duplicate). */ + transferSettled: number + /** Items still meant to be transferred (everything except transfer-cancelled). */ + transferTotal: number + /** Items that reached the server. */ + uploaded: number + totalBytes: number + /** Bytes no longer waiting to be sent: settled items in full plus in-flight progress. */ + loadedBytes: number + /** + * Bytes that actually crossed the wire to a live or successful request. Unlike + * loadedBytes it never jumps when a file fails, so it is what speed is measured on. + */ + sentBytes: number + /** Failed or cancelled transfers that can be queued again. */ + retryable: number + stage: UploadStage + /** Stacked progress bar widths, each 0..1 of the non-cancelled items. */ + bar: { ready: number; active: number; failed: number; duplicate: number } +} + +export function summarizeItems(items: readonly UploadItem[]): UploadSummary { + const summary: UploadSummary = { + total: items.length, + waiting: 0, + uploading: 0, + parsing: 0, + ready: 0, + failed: 0, + duplicate: 0, + cancelled: 0, + transferSettled: 0, + transferTotal: 0, + uploaded: 0, + totalBytes: 0, + loadedBytes: 0, + sentBytes: 0, + retryable: 0, + stage: 'done', + bar: { ready: 0, active: 0, failed: 0, duplicate: 0 }, + } + let inFlightUnits = 0 + + for (const item of items) { + const phase = itemPhase(item) + switch (phase) { + case 'waiting': + summary.waiting++ + break + case 'uploading': + case 'saving': + summary.uploading++ + if (item.size > 0) inFlightUnits += Math.min(1, item.loaded / item.size) + break + default: + summary[phase]++ + } + + if (item.transfer === 'cancelled') { + summary.retryable++ + continue + } + summary.transferTotal++ + summary.totalBytes += item.size + if (item.transfer === 'uploaded' || item.transfer === 'failed' || item.transfer === 'duplicate') { + summary.transferSettled++ + summary.loadedBytes += item.size + if (item.transfer !== 'failed') summary.sentBytes += item.size + } else if (item.transfer === 'uploading') { + summary.loadedBytes += Math.min(item.loaded, item.size) + summary.sentBytes += Math.min(item.loaded, item.size) + } + if (item.transfer === 'uploaded') summary.uploaded++ + if (item.transfer === 'failed') summary.retryable++ + } + + if (summary.waiting + summary.uploading > 0) summary.stage = 'uploading' + else if (summary.parsing > 0) summary.stage = 'parsing' + + const denominator = summary.total - summary.cancelled + if (denominator > 0) { + summary.bar = { + ready: summary.ready / denominator, + active: (summary.parsing + inFlightUnits) / denominator, + failed: summary.failed / denominator, + duplicate: summary.duplicate / denominator, + } + } + return summary +} + +/** + * Queued items to start now so that no more than `concurrency` transfers run + * at once. Items sharing a `conflictKey` with a running or just-picked item + * wait their turn, and the next free slot goes to a later item instead. + */ +export function pickNextToStart( + items: readonly T[], + concurrency: number, + conflictKey?: (item: T) => string, +): T[] { + let running = 0 + const busyKeys = new Set() + for (const item of items) { + if (item.transfer !== 'uploading') continue + running++ + if (conflictKey) busyKeys.add(conflictKey(item)) + } + const picked: T[] = [] + for (const item of items) { + if (running >= concurrency) break + if (item.transfer !== 'queued') continue + const key = conflictKey?.(item) + if (key !== undefined) { + if (busyKeys.has(key)) continue + busyKeys.add(key) + } + picked.push(item) + running++ + } + return picked +} + +export type UploadOutcome = + | { kind: 'uploaded'; knowledgeId?: string; parseStatus?: string } + | { kind: 'duplicate'; knowledgeId?: string; message?: string } + | { kind: 'failed'; message?: string } + +/** + * Classify a resolved or rejected upload call. request.ts rejects non-2xx + * responses with the JSON body spread over `{ status, message }`, so a 409 + * duplicate arrives as a rejection carrying `code` and the existing row in `data`. + */ +export function classifyUploadResult(result: any): UploadOutcome { + const code = result?.code ?? result?.error?.code + if (code === 'duplicate_file') { + return { kind: 'duplicate', knowledgeId: result?.data?.id, message: result?.message } + } + if (result?.success === true) { + return { kind: 'uploaded', knowledgeId: result?.data?.id, parseStatus: result?.data?.parse_status } + } + return { kind: 'failed', message: result?.error?.message || result?.message } +} + +export interface RateSample { + at: number + bytes: number +} + +/** + * Bytes per second over the samples inside `windowMs` of the newest one. + * Returns 0 until the window spans at least one second, so a first burst of + * buffered progress events doesn't produce a wildly optimistic ETA. + */ +export function estimateRate(samples: readonly RateSample[], windowMs = 8000): number { + if (samples.length < 2) return 0 + const newest = samples[samples.length - 1] + const oldest = samples.find(sample => newest.at - sample.at <= windowMs) ?? newest + const elapsed = newest.at - oldest.at + if (elapsed < 1000) return 0 + return Math.max(0, (newest.bytes - oldest.bytes) / (elapsed / 1000)) +} + +/** Remaining seconds, or null when there is no usable rate yet. */ +export function estimateRemainingSeconds(remainingBytes: number, bytesPerSecond: number): number | null { + if (bytesPerSecond <= 0 || remainingBytes <= 0) return null + return Math.ceil(remainingBytes / bytesPerSecond) +} + +/** + * The coarse unit an ETA is read in. Seconds round up to 5 so the number + * doesn't flicker every tick; hours keep one decimal. + */ +export function splitDuration(seconds: number): { unit: 'seconds' | 'minutes' | 'hours'; value: number } { + if (seconds <= 55) return { unit: 'seconds', value: Math.max(5, Math.ceil(seconds / 5) * 5) } + if (seconds < 3600) return { unit: 'minutes', value: Math.ceil(seconds / 60) } + return { unit: 'hours', value: Math.round(seconds / 360) / 10 } +} diff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vue index c6203e1a..21034d1e 100644 --- a/frontend/src/views/knowledge/KnowledgeBase.vue +++ b/frontend/src/views/knowledge/KnowledgeBase.vue @@ -28,7 +28,6 @@ import { batchQueryKnowledge, listKnowledgeTags, updateKnowledgeTagBatch, - uploadKnowledgeFile, createKnowledgeFromURL, reparseKnowledge, cancelKnowledgeParse, @@ -58,6 +57,7 @@ import BatchTagDialog from './components/BatchTagDialog.vue'; import KbTagManageDrawer from './components/KbTagManageDrawer.vue'; import type { KnowledgeProcessOverrides } from '@/types/knowledgeProcess'; import { useUploadConfirmStore, type UploadConfirmResult } from '@/stores/uploadConfirm'; +import { useUploadTasksStore } from '@/stores/uploadTasks'; import WikiBrowser from './wiki/WikiBrowser.vue'; import { getWikiStats } from '@/api/wiki'; import { @@ -74,7 +74,6 @@ import { folderBreadcrumbs as buildFolderBreadcrumbs, folderPathExists as folderExistsInTree, isFilteringDocuments, - isFolderUpload, ROOT_FOLDER_PATH, } from './folderTree'; import { useI18n } from 'vue-i18n'; @@ -85,7 +84,6 @@ const { t } = useI18n(); const kbId = computed(() => (route.params as any).kbId as string || ''); const kbInfo = ref(null); const uploadSourceRef = ref | null>(null); -const uploading = ref(false); const kbLoading = ref(false); const docListLoading = ref(true); const isFAQ = computed(() => (kbInfo.value?.type || '') === 'faq'); @@ -1178,12 +1176,18 @@ const handleFileUploaded = (event: CustomEvent) => { const uploadedKbId = event.detail.kbId; console.log('接收到文件上传事件,上传的知识库ID:', uploadedKbId, '当前知识库ID:', kbId.value); if (uploadedKbId && uploadedKbId === kbId.value && !isFAQ.value) { + // Mid-batch refreshes (settled === false) only bring new rows and folders + // in, and are skipped once the user scrolled past the first page because + // reloading resets the list to it. The batch's final event refreshes fully. + const midBatch = event.detail.settled === false; + if (midBatch && page > 1) return; console.log('匹配当前知识库,开始刷新文件列表'); // 如果上传的文件属于当前知识库,使用 loadKnowledgeFiles 刷新文件列表 resetPage(); // Reset page counter when reloading files after upload loadKnowledgeFiles(uploadedKbId); - loadTags(uploadedKbId); void loadFolderTree(uploadedKbId); + if (midBatch) return; + loadTags(uploadedKbId); // 启动几次探测,尽快让面包屑的"索引中"亮起。 scheduleWikiStatusProbes(); } @@ -1591,43 +1595,11 @@ const AUDIO_EXTENSIONS = ['mp3', 'wav', 'm4a', 'flac', 'ogg']; const uploadConfirmStore = useUploadConfirmStore(); -const getFolderUploadFileName = (file: File, targetFolder: string) => - buildUploadFileName(file, targetFolder); +const uploadTasksStore = useUploadTasksStore(); -const showUploadResultMessages = ( - successCount: number, - failCount: number, - totalCount: number, - mode: 'document' | 'folder', -) => { - if (mode === 'folder') { - if (failCount === 0) { - MessagePlugin.success(t('knowledgeBase.uploadAllSuccess', { count: successCount })); - } else if (successCount > 0) { - MessagePlugin.warning(t('knowledgeBase.uploadPartialSuccess', { success: successCount, fail: failCount })); - } else { - MessagePlugin.error(t('knowledgeBase.uploadAllFailed')); - } - return; - } - - if (totalCount === 1) { - if (successCount === 1) { - MessagePlugin.success(t('knowledgeBase.uploadSuccess')); - } - return; - } - - if (failCount === 0) { - MessagePlugin.success(t('knowledgeBase.allUploadSuccess', { count: successCount })); - } else if (successCount > 0) { - MessagePlugin.warning(t('knowledgeBase.partialUploadSuccess', { success: successCount, fail: failCount })); - } else { - MessagePlugin.error(t('knowledgeBase.allUploadFailed', { count: failCount })); - } -}; - -const executeUploadBatch = async ( +// Hands the batch to the global upload queue, which runs the transfers, +// reports progress in its floating panel and refreshes this page as files land. +const enqueueUploads = ( files: File[], options: { processConfig?: KnowledgeProcessOverrides; @@ -1637,72 +1609,16 @@ const executeUploadBatch = async ( } = {}, ) => { const targetKbId = kbId.value; - if (!targetKbId || files.length === 0) { - return { successCount: 0, failCount: files.length }; - } - - const tagIdsToUpload = options.tagIds && options.tagIds.length > 0 - ? [...options.tagIds] - : undefined; - let successCount = 0; - let failCount = 0; - const totalCount = files.length; - const hasFolderPaths = files.some(isFolderUpload); - - for (const file of files) { - try { - const uploadData: { - file: File - tag_ids?: string[] - fileName?: string - process_config?: KnowledgeProcessOverrides - } = { file, tag_ids: tagIdsToUpload }; - - const fileName = getFolderUploadFileName(file, options.targetFolder || ROOT_FOLDER_PATH); - if (fileName) uploadData.fileName = fileName; - if (options.processConfig) { - uploadData.process_config = options.processConfig; - } - - const responseData: any = await uploadKnowledgeFile(targetKbId, uploadData); - const isSuccess = responseData?.success || responseData?.code === 200 || responseData?.status === 'success' || (!responseData?.error && responseData); - if (isSuccess) { - successCount++; - } else { - failCount++; - if (totalCount === 1) { - let errorMessage = t('knowledgeBase.uploadFailed'); - if (responseData?.error?.message) { - errorMessage = responseData.error.message; - } else if (responseData?.message) { - errorMessage = responseData.message; - } - if (responseData?.code === 'duplicate_file' || responseData?.error?.code === 'duplicate_file') { - errorMessage = t('knowledgeBase.fileExists'); - } - MessagePlugin.error(errorMessage); - } - } - } catch (error: any) { - failCount++; - if (totalCount === 1) { - let errorMessage = error?.error?.message || error?.message || t('knowledgeBase.uploadFailed'); - if (error?.code === 'duplicate_file') { - errorMessage = t('knowledgeBase.fileExists'); - } - MessagePlugin.error(errorMessage); - } - } - } - - if (successCount > 0) { - window.dispatchEvent(new CustomEvent('knowledgeFileUploaded', { - detail: { kbId: targetKbId }, - })); - } - - showUploadResultMessages(successCount, failCount, totalCount, hasFolderPaths ? 'folder' : 'document'); - return { successCount, failCount }; + if (!targetKbId || files.length === 0) return; + const targetFolder = options.targetFolder || ROOT_FOLDER_PATH; + uploadTasksStore.enqueue({ + kbId: targetKbId, + kbName: kbInfo.value?.name || '', + targetFolder, + tagIds: options.tagIds, + processConfig: options.processConfig, + uploads: files.map(file => ({ file, fileName: buildUploadFileName(file, targetFolder) })), + }); }; const executeUrlImport = async ( @@ -1761,11 +1677,7 @@ const handleUploadConfirmResult = async (result: UploadConfirmResult) => { const tagIds = result.tagIds || []; if (files.length > 0) { - const hasFolderPaths = files.some(isFolderUpload); - if (hasFolderPaths) { - MessagePlugin.info(t('knowledgeBase.uploadingFolder', { total: files.length })); - } - await executeUploadBatch(files, { + enqueueUploads(files, { processConfig, tagIds, targetFolder: result.targetFolder || ROOT_FOLDER_PATH, diff --git a/frontend/src/views/knowledge/KnowledgeBaseList.vue b/frontend/src/views/knowledge/KnowledgeBaseList.vue index 2fa64e7c..792be226 100644 --- a/frontend/src/views/knowledge/KnowledgeBaseList.vue +++ b/frontend/src/views/knowledge/KnowledgeBaseList.vue @@ -32,44 +32,6 @@ {{ $t('knowledgeList.uninitializedBanner') }} - -
-
-
- -
-
-
- {{ - summary.completed === summary.total - ? $t('knowledgeList.uploadProgress.completedTitle', { name: summary.kbName }) - : $t('knowledgeList.uploadProgress.uploadingTitle', { name: summary.kbName }) - }} -
-
- {{ - summary.completed === summary.total - ? $t('knowledgeList.uploadProgress.completedDetail', { total: summary.total }) - : $t('knowledgeList.uploadProgress.detail', { completed: summary.completed, total: summary.total }) - }} -
-
- {{ - summary.completed === summary.total - ? $t('knowledgeList.uploadProgress.refreshing') - : $t('knowledgeList.uploadProgress.keepPageOpen') - }} -
-
- {{ $t('knowledgeList.uploadProgress.errorTip') }} -
-
-
-
-
-
-
-
@@ -843,10 +805,7 @@ const confirmDelete = useConfirmDelete() const currentMoreIndex = ref(-1) const highlightedKbId = ref(null) const highlightedCardRef = ref(null) -const uploadTasks = ref([]) -const uploadCleanupTimers = new Map>() let uploadRefreshTimer: ReturnType | null = null -const UPLOAD_CLEANUP_DELAY = 10000 // Share dialog state const shareDialogVisible = ref(false) @@ -1163,24 +1122,6 @@ const showKbListContextualGuide = computed( () => showKbListEmpty.value && !uiStore.showKBEditorModal, ) -interface UploadTaskState { - uploadId: string - kbId: string - fileName?: string - progress: number - status: 'uploading' | 'success' | 'error' - error?: string -} - -interface UploadSummary { - kbId: string - kbName: string - total: number - completed: number - progress: number - hasError: boolean -} - const applyKbListData = (data: any[]) => { kbs.value = data.map((kb: any) => ({ ...kb, @@ -1255,20 +1196,12 @@ onMounted(() => { } }) - window.addEventListener('knowledgeFileUploadStart', handleUploadStartEvent as EventListener) - window.addEventListener('knowledgeFileUploadProgress', handleUploadProgressEvent as EventListener) - window.addEventListener('knowledgeFileUploadComplete', handleUploadCompleteEvent as EventListener) window.addEventListener('knowledgeFileUploaded', handleUploadFinishedEvent as EventListener) }) onUnmounted(() => { - window.removeEventListener('knowledgeFileUploadStart', handleUploadStartEvent as EventListener) - window.removeEventListener('knowledgeFileUploadProgress', handleUploadProgressEvent as EventListener) - window.removeEventListener('knowledgeFileUploadComplete', handleUploadCompleteEvent as EventListener) window.removeEventListener('knowledgeFileUploaded', handleUploadFinishedEvent as EventListener) - uploadCleanupTimers.forEach(timer => clearTimeout(timer)) - uploadCleanupTimers.clear() if (uploadRefreshTimer) { clearTimeout(uploadRefreshTimer) uploadRefreshTimer = null @@ -1533,101 +1466,6 @@ const hasUninitializedKbs = computed(() => { return kbs.value.some(kb => !isInitialized(kb)) }) -const getKbDisplayName = (kbId: string) => { - const target = kbs.value.find(kb => kb.id === kbId) - if (target?.name) return target.name - return t('knowledgeList.uploadProgress.unknownKb', { id: kbId }) as string -} - -const uploadSummaries = computed(() => { - if (!uploadTasks.value.length) return [] - const grouped: Record = {} - uploadTasks.value.forEach(task => { - const kbKey = String(task.kbId) - if (!grouped[kbKey]) grouped[kbKey] = [] - grouped[kbKey].push(task) - }) - return Object.entries(grouped).map(([kbId, tasks]) => { - const total = tasks.length - const completed = tasks.filter(task => task.status !== 'uploading').length - const progressSum = tasks.reduce((sum, task) => sum + (task.progress ?? 0), 0) - const avgProgress = total === 0 ? 0 : Math.min(100, Math.max(0, Math.round(progressSum / total))) - const hasError = tasks.some(task => task.status === 'error') - return { - kbId, - kbName: getKbDisplayName(kbId), - total, - completed, - progress: avgProgress, - hasError - } - }).sort((a, b) => a.kbName.localeCompare(b.kbName)) -}) - -const clampProgress = (value: number) => Math.min(100, Math.max(0, Math.round(value))) - -const addUploadTask = (task: UploadTaskState) => { - uploadTasks.value = [ - ...uploadTasks.value.filter(item => item.uploadId !== task.uploadId), - task, - ] -} - -const patchUploadTask = (uploadId: string, patch: Partial) => { - const index = uploadTasks.value.findIndex(task => task.uploadId === uploadId) - if (index === -1) return - const nextTasks = [...uploadTasks.value] - nextTasks[index] = { ...nextTasks[index], ...patch } - uploadTasks.value = nextTasks -} - -const removeUploadTask = (uploadId: string) => { - uploadTasks.value = uploadTasks.value.filter(task => task.uploadId !== uploadId) - const timer = uploadCleanupTimers.get(uploadId) - if (timer) { - clearTimeout(timer) - uploadCleanupTimers.delete(uploadId) - } -} - -const scheduleUploadTaskCleanup = (uploadId: string) => { - const existing = uploadCleanupTimers.get(uploadId) - if (existing) { - clearTimeout(existing) - } - const timer = setTimeout(() => { - removeUploadTask(uploadId) - }, UPLOAD_CLEANUP_DELAY) - uploadCleanupTimers.set(uploadId, timer) -} - -type UploadEventDetail = { - uploadId: string - kbId?: string | number - fileName?: string - progress?: number - status?: UploadTaskState['status'] - error?: string -} - -const ensureUploadTaskEntry = (detail?: UploadEventDetail) => { - if (!detail?.uploadId) return null - const existing = uploadTasks.value.find(task => task.uploadId === detail.uploadId) - if (existing) return existing - if (!detail.kbId) return null - const initialProgress = typeof detail.progress === 'number' ? clampProgress(detail.progress) : 0 - const newTask: UploadTaskState = { - uploadId: detail.uploadId, - kbId: String(detail.kbId), - fileName: detail.fileName, - progress: initialProgress, - status: detail.status || 'uploading', - error: detail.error - } - addUploadTask(newTask) - return newTask -} - const handleCardClick = (kb: KB) => { // Track this open in the per-user "recent" list before navigating — // matches the user mental model "this is what I last worked on". @@ -1703,45 +1541,12 @@ const triggerHighlightFlash = (kbId: string) => { }) } -const handleUploadStartEvent = (event: Event) => { - const detail = (event as CustomEvent).detail - if (!detail?.uploadId || !detail?.kbId) return - addUploadTask({ - uploadId: detail.uploadId, - kbId: String(detail.kbId), - fileName: detail.fileName, - progress: typeof detail.progress === 'number' ? clampProgress(detail.progress) : 0, - status: 'uploading' - }) -} - -const handleUploadProgressEvent = (event: Event) => { - const detail = (event as CustomEvent).detail - if (!detail?.uploadId || typeof detail.progress !== 'number') return - if (!ensureUploadTaskEntry(detail)) return - patchUploadTask(detail.uploadId, { - progress: clampProgress(detail.progress) - }) -} - -const handleUploadCompleteEvent = (event: Event) => { - const detail = (event as CustomEvent).detail - if (!detail?.uploadId) return - const progress = typeof detail.progress === 'number' - ? clampProgress(detail.progress) - : 100 - if (!ensureUploadTaskEntry({ ...detail, progress })) return - patchUploadTask(detail.uploadId, { - status: detail.status || 'success', - progress, - error: detail.error - }) - scheduleUploadTaskCleanup(detail.uploadId) -} - const handleUploadFinishedEvent = (event: Event) => { - const detail = (event as CustomEvent<{ kbId?: string | number }>).detail + const detail = (event as CustomEvent<{ kbId?: string | number; settled?: boolean }>).detail if (!detail?.kbId) return + // Counts only need the batch's final refresh; a forced reload every couple + // of seconds mid-batch would also close any open card menu. + if (detail.settled === false) return if (uploadRefreshTimer) { clearTimeout(uploadRefreshTimer) } @@ -2068,75 +1873,6 @@ const handleUploadFinishedEvent = (event: Event) => { } } -.upload-progress-panel { - display: flex; - flex-direction: column; - gap: 12px; - margin-bottom: 20px; -} - -.upload-progress-item { - display: flex; - align-items: center; - gap: 12px; - padding: 12px 16px; - border: 1px solid var(--td-component-stroke); - border-radius: var(--app-radius-md); - background: var(--td-bg-color-container); -} - -.upload-progress-icon { - color: var(--td-brand-color); - display: flex; - align-items: center; - justify-content: center; -} - -.upload-progress-content { - flex: 1; -} - -.progress-title { - color: var(--td-text-color-primary); - font-family: var(--app-font-family); - font-size: var(--app-text-base); - font-weight: 600; - line-height: 22px; - margin-bottom: 2px; -} - -.progress-subtitle { - color: var(--td-text-color-secondary); - font-family: var(--app-font-family); - font-size: var(--app-text-sm); - line-height: 18px; -} - -.progress-subtitle.secondary { - color: var(--td-text-color-placeholder); - margin-top: 2px; -} - -.progress-subtitle.error { - color: var(--td-error-color); - margin-top: 4px; -} - -.progress-bar { - width: 100%; - height: 6px; - border-radius: var(--app-radius-pill); - background: var(--td-bg-color-secondarycontainer); - margin-top: 10px; - overflow: hidden; -} - -.progress-bar-inner { - height: 100%; - background: linear-gradient(90deg, var(--td-brand-color-active) 0%, var(--td-brand-color) 100%); - transition: width var(--app-motion-base) ease; -} - @keyframes contentFadeIn { from { opacity: 0; diff --git a/frontend/src/views/knowledge/components/UploadConfirmDialog.test.ts b/frontend/src/views/knowledge/components/UploadConfirmDialog.test.ts index 312c6801..7b83c162 100644 --- a/frontend/src/views/knowledge/components/UploadConfirmDialog.test.ts +++ b/frontend/src/views/knowledge/components/UploadConfirmDialog.test.ts @@ -17,7 +17,7 @@ test('selects multiple document tags and returns them with the confirmation resu test('uses confirmed tags for file and URL imports instead of reading the list filter at upload time', () => { assert.match(knowledgeBase, /const tagIds = result\.tagIds \|\| \[\]/) - assert.match(knowledgeBase, /executeUploadBatch\(files, \{[\s\S]*?\btagIds,[\s\S]*?\}\)/) + assert.match(knowledgeBase, /enqueueUploads\(files, \{[\s\S]*?\btagIds,[\s\S]*?\}\)/) assert.match(knowledgeBase, /executeUrlImport\(url, processConfig, tagIds\)/) assert.doesNotMatch( knowledgeBase, diff --git a/frontend/src/views/platform/index.vue b/frontend/src/views/platform/index.vue index cb7ec523..6072f882 100644 --- a/frontend/src/views/platform/index.vue +++ b/frontend/src/views/platform/index.vue @@ -14,6 +14,8 @@ + +
@@ -26,6 +28,7 @@ import UploadMask from '@/components/upload-mask.vue' import Settings from '@/views/settings/Settings.vue' import GlobalCommandPalette from '@/components/GlobalCommandPalette.vue' import GlobalInvitationBell from '@/components/GlobalInvitationBell.vue' +import UploadTasksPanel from '@/components/upload-tasks/UploadTasksPanel.vue' import NewUserGuide from '@/components/NewUserGuide.vue' import { useCommandPaletteStore } from '@/stores/commandPalette' import { useChatResourcesStore } from '@/stores/chatResources'