feat(frontend): show overall progress for knowledge file uploads (#3399)
* feat(frontend): show overall progress for knowledge file uploads Batch uploads ran one file at a time with no feedback until the whole batch finished, and nothing followed the asynchronous parse afterwards. The knowledge base list still carried a progress panel whose event emitter was removed with the old menu upload flow, so it never showed. - Run uploads through a global queue (stores/uploadQueue.ts, wired to the API in stores/uploadTasks.ts): three concurrent transfers, per-file cancel that aborts the request, retry for failed or cancelled files, and polling of the created knowledge rows until parsing settles. finalizing counts as searchable. - Add a floating panel (components/upload-tasks/) mounted in the platform shell: stage headline with a progress ring, bytes and ETA while uploading, a stacked bar for searchable / in progress / failed / duplicate, per-file status with hover actions (cancel, retry, open the document), an issues filter, grouping by batch, collapse, a confirm before closing mid-upload, and auto-dismiss after a clean finish. - Warn before unloading the page while transfers are still running. - Refresh an open knowledge base list as files land (throttled), but skip mid-batch reloads while the user has scrolled past the first page; the batch's final refresh always runs. - Remove the orphaned list-page panel, the unused useKnowledgeBase requestMethod, the per-batch toasts and the i18n keys they leave unused. * fix(frontend): harden the upload queue's wiring into the app Review of the upload progress panel found the store misbehaving once connected to real auth and page events: - The owner watch used one getter returning a fresh array, so every setUser() fired it, even for the same person (opening the user menu, hovering the workspace submenu), and dismissed running uploads. Watch the user id and tenant id as separate sources. - Starting a new batch after the previous run finished cleared it whole, including failed files still waiting for Retry. Only batches whose every file is searchable are dropped now. - The knowledge base list page reloaded everything on each mid-batch refresh (about every 2s), closing open card menus. It now waits for the batch's final event; the detail page's mid-batch refreshes only reload files and folders, and tags and wiki probes wait for the end. - A row missing from one successful status poll was marked deleted for good. It now takes three consecutive misses, reset when it reappears. - Closing the panel aborted requests whose body was already sent, which the server still stores. Those are left to finish and trigger a list refresh when they land. - Two identical files in one batch could both pass the server's hash dedup when uploaded in parallel. Same-size files for one knowledge base now never run at once, so the second sees the first's row. Also: detect cancellation from the abort signal instead of the item state, ignore a cancelled attempt that settles after its retry started, bind the beforeunload guard to the panel's lifetime, and show the subfolder next to file names from folder uploads. The store body moves into uploadTasksCore.ts with the API, events and identity injected, so the owner watch and enqueue policy are tested alongside the queue.main
parent
a9c85fd17e
commit
9d508c1c7a
|
|
@ -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创建知识
|
||||
|
|
|
|||
|
|
@ -0,0 +1,67 @@
|
|||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
/** 0..1 */
|
||||
value: number
|
||||
size?: number
|
||||
stroke?: number
|
||||
}>(), {
|
||||
size: 20,
|
||||
stroke: 2.5,
|
||||
})
|
||||
|
||||
const radius = computed(() => (props.size - props.stroke) / 2)
|
||||
const circumference = computed(() => 2 * Math.PI * radius.value)
|
||||
const offset = computed(() => circumference.value * (1 - Math.min(1, Math.max(0, props.value))))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<svg
|
||||
class="progress-ring"
|
||||
:width="size"
|
||||
:height="size"
|
||||
:viewBox="`0 0 ${size} ${size}`"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<circle
|
||||
class="progress-ring-track"
|
||||
:cx="size / 2"
|
||||
:cy="size / 2"
|
||||
:r="radius"
|
||||
:stroke-width="stroke"
|
||||
/>
|
||||
<circle
|
||||
v-if="value > 0"
|
||||
class="progress-ring-value"
|
||||
:cx="size / 2"
|
||||
:cy="size / 2"
|
||||
:r="radius"
|
||||
:stroke-width="stroke"
|
||||
:stroke-dasharray="circumference"
|
||||
:stroke-dashoffset="offset"
|
||||
/>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<style scoped lang="less">
|
||||
.progress-ring {
|
||||
display: block;
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
|
||||
.progress-ring-track,
|
||||
.progress-ring-value {
|
||||
fill: none;
|
||||
}
|
||||
|
||||
.progress-ring-track {
|
||||
stroke: color-mix(in srgb, currentColor 18%, transparent);
|
||||
}
|
||||
|
||||
.progress-ring-value {
|
||||
stroke: currentColor;
|
||||
stroke-linecap: round;
|
||||
transition: stroke-dashoffset var(--app-motion-slow) ease;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -0,0 +1,308 @@
|
|||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { formatFileSize, getFileIcon } from '@/utils/files'
|
||||
import { itemPhase, type UploadItem } from '@/stores/uploadTasksState'
|
||||
import ProgressRing from './ProgressRing.vue'
|
||||
|
||||
const props = defineProps<{ item: UploadItem }>()
|
||||
const emit = defineEmits<{
|
||||
cancel: [id: string]
|
||||
retry: [id: string]
|
||||
open: [item: UploadItem]
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const phase = computed(() => itemPhase(props.item))
|
||||
/** Folder uploads repeat names like README.md; the subfolder tells them apart. */
|
||||
const folder = computed(() => props.item.relativePath.split('/').slice(0, -1).join('/'))
|
||||
const ratio = computed(() => (props.item.size > 0 ? props.item.loaded / props.item.size : 0))
|
||||
const bytes = (value: number) => formatFileSize(value) || '0 B'
|
||||
|
||||
type RowAction = 'cancel' | 'retry' | 'open'
|
||||
|
||||
const action = computed<RowAction | null>(() => {
|
||||
const { item } = props
|
||||
switch (phase.value) {
|
||||
case 'waiting':
|
||||
case 'uploading':
|
||||
return 'cancel'
|
||||
case 'saving':
|
||||
return null
|
||||
case 'failed':
|
||||
case 'cancelled':
|
||||
if (item.transfer === 'failed' || item.transfer === 'cancelled') return 'retry'
|
||||
return item.knowledgeId && item.parseStatus !== 'deleted' ? 'open' : null
|
||||
default:
|
||||
return item.knowledgeId ? 'open' : null
|
||||
}
|
||||
})
|
||||
|
||||
const actionMeta: Record<RowAction, { icon: string; label: string }> = {
|
||||
cancel: { icon: 'close', label: 'uploadTasks.cancel' },
|
||||
retry: { icon: 'refresh', label: 'uploadTasks.retry' },
|
||||
open: { icon: 'chevron-right', label: 'uploadTasks.open' },
|
||||
}
|
||||
|
||||
/** Failure reason, shown after the phase label and in full on hover. */
|
||||
const reason = computed(() => {
|
||||
if (phase.value !== 'failed') return ''
|
||||
return (props.item.transfer === 'failed' ? props.item.error : props.item.parseError) || ''
|
||||
})
|
||||
|
||||
const meta = computed(() => {
|
||||
const { item } = props
|
||||
switch (phase.value) {
|
||||
case 'waiting':
|
||||
return `${t('uploadTasks.phaseWaiting')} · ${bytes(item.size)}`
|
||||
case 'uploading':
|
||||
return `${bytes(item.loaded)} / ${bytes(item.size)}`
|
||||
case 'saving':
|
||||
return t('uploadTasks.phaseSaving')
|
||||
case 'parsing':
|
||||
return t(item.parseStatus === 'processing' ? 'uploadTasks.phaseParsing' : 'uploadTasks.phasePending')
|
||||
case 'ready':
|
||||
return t(item.parseStatus === 'finalizing' ? 'uploadTasks.phaseFinalizing' : 'uploadTasks.phaseReady')
|
||||
case 'failed': {
|
||||
const label = t(item.transfer === 'failed' ? 'uploadTasks.phaseUploadFailed' : 'uploadTasks.phaseParseFailed')
|
||||
return reason.value ? `${label} · ${reason.value}` : label
|
||||
}
|
||||
case 'duplicate':
|
||||
return t('uploadTasks.phaseDuplicate')
|
||||
case 'cancelled':
|
||||
return t(item.parseStatus === 'deleted' ? 'uploadTasks.phaseDeleted' : 'uploadTasks.phaseCancelled')
|
||||
}
|
||||
return ''
|
||||
})
|
||||
|
||||
const runAction = () => {
|
||||
if (action.value === 'cancel') emit('cancel', props.item.id)
|
||||
else if (action.value === 'retry') emit('retry', props.item.id)
|
||||
else if (action.value === 'open') emit('open', props.item)
|
||||
}
|
||||
|
||||
const handleRowClick = () => {
|
||||
if (action.value === 'open') emit('open', props.item)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="upload-task-row"
|
||||
:class="[`is-${phase}`, { 'is-openable': action === 'open' }]"
|
||||
@click="handleRowClick"
|
||||
>
|
||||
<span class="row-file-icon" aria-hidden="true">
|
||||
<t-icon :name="getFileIcon(item.name)" />
|
||||
</span>
|
||||
<span class="row-main">
|
||||
<span class="row-name" :title="item.relativePath || item.name">
|
||||
<span class="row-name-text">{{ item.name }}</span>
|
||||
<span v-if="folder" class="row-name-folder">{{ folder }}</span>
|
||||
</span>
|
||||
<span class="row-meta" :title="reason || undefined">{{ meta }}</span>
|
||||
</span>
|
||||
<span class="row-end">
|
||||
<span class="row-status" :class="{ 'has-action': !!action }" aria-hidden="true">
|
||||
<ProgressRing v-if="phase === 'uploading'" :value="ratio" :size="20" :stroke="2.5" />
|
||||
<t-icon v-else-if="phase === 'waiting'" name="time" />
|
||||
<t-icon v-else-if="phase === 'saving' || phase === 'parsing'" name="loading" class="row-spin" />
|
||||
<t-icon v-else-if="phase === 'ready'" name="check-circle-filled" />
|
||||
<t-icon v-else-if="phase === 'failed'" name="error-circle-filled" />
|
||||
<t-icon v-else-if="phase === 'duplicate'" name="info-circle-filled" />
|
||||
<t-icon v-else name="minus-circle" />
|
||||
</span>
|
||||
<button
|
||||
v-if="action"
|
||||
type="button"
|
||||
class="row-action"
|
||||
:aria-label="t(actionMeta[action].label)"
|
||||
:title="t(actionMeta[action].label)"
|
||||
@click.stop="runAction"
|
||||
>
|
||||
<t-icon :name="actionMeta[action].icon" />
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="less">
|
||||
.upload-task-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--app-space-3);
|
||||
padding: var(--app-space-2);
|
||||
border-radius: var(--app-radius-md);
|
||||
transition: background-color var(--app-motion-fast) ease;
|
||||
|
||||
&:hover,
|
||||
&:focus-within {
|
||||
background: var(--td-bg-color-container-hover);
|
||||
}
|
||||
|
||||
&.is-openable {
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
.row-file-icon {
|
||||
display: grid;
|
||||
flex-shrink: 0;
|
||||
place-items: center;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-2xl);
|
||||
}
|
||||
|
||||
.row-main {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.row-name-text,
|
||||
.row-name-folder,
|
||||
.row-meta {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.row-name {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
color: var(--td-text-color-primary);
|
||||
font-size: var(--app-text-md);
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.row-name-text {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
// Gives way long before the file name does.
|
||||
.row-name-folder {
|
||||
flex: 0 100 auto;
|
||||
min-width: 0;
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-sm);
|
||||
}
|
||||
|
||||
.row-meta {
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-sm);
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 18px;
|
||||
|
||||
.is-failed & {
|
||||
color: var(--td-error-color);
|
||||
}
|
||||
|
||||
.is-duplicate & {
|
||||
color: var(--td-warning-color);
|
||||
}
|
||||
}
|
||||
|
||||
.row-end {
|
||||
display: grid;
|
||||
flex-shrink: 0;
|
||||
place-items: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
|
||||
> * {
|
||||
grid-area: 1 / 1;
|
||||
}
|
||||
}
|
||||
|
||||
.row-status {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-xl);
|
||||
|
||||
.is-uploading &,
|
||||
.is-saving &,
|
||||
.is-parsing &,
|
||||
.is-ready & {
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
.is-failed & {
|
||||
color: var(--td-error-color);
|
||||
}
|
||||
|
||||
.is-duplicate & {
|
||||
color: var(--td-warning-color);
|
||||
}
|
||||
}
|
||||
|
||||
.row-spin {
|
||||
animation: wk-spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
.row-action {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: transparent;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-xl);
|
||||
cursor: pointer;
|
||||
opacity: 0;
|
||||
transition: opacity var(--app-motion-fast) ease, background-color var(--app-motion-fast) ease;
|
||||
|
||||
&:hover {
|
||||
background: var(--td-bg-color-container-active);
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--td-brand-color);
|
||||
outline-offset: -2px;
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
// The status icon and the row action share one slot: hovering (or focusing)
|
||||
// a row swaps the indicator for what the user can do about it.
|
||||
.upload-task-row:hover,
|
||||
.upload-task-row:focus-within {
|
||||
.row-status.has-action {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.row-action {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Without hover there is no way to discover the swap, so show actions outright.
|
||||
@media (hover: none) {
|
||||
.row-status.has-action {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.row-action {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.row-spin {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
|
@ -0,0 +1,720 @@
|
|||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { useUploadTasksStore, type UploadBatch } from '@/stores/uploadTasks'
|
||||
import {
|
||||
estimateRate,
|
||||
estimateRemainingSeconds,
|
||||
itemPhase,
|
||||
splitDuration,
|
||||
type RateSample,
|
||||
type UploadItem,
|
||||
} from '@/stores/uploadTasksState'
|
||||
import { formatFileSize } from '@/utils/files'
|
||||
import ProgressRing from './ProgressRing.vue'
|
||||
import UploadTaskRow from './UploadTaskRow.vue'
|
||||
|
||||
/** A run that finished cleanly leaves on its own after this long without hover. */
|
||||
const AUTO_DISMISS_MS = 6000
|
||||
|
||||
const { t } = useI18n()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const store = useUploadTasksStore()
|
||||
const { items, batches, summary, visible, collapsed } = storeToRefs(store)
|
||||
|
||||
const hovering = ref(false)
|
||||
const filter = ref<'all' | 'issues'>('all')
|
||||
|
||||
// A panel dismissed under the pointer never sees mouseleave.
|
||||
watch(visible, shown => {
|
||||
if (!shown) hovering.value = false
|
||||
})
|
||||
|
||||
const issueCount = computed(() => summary.value.failed + summary.value.duplicate + summary.value.cancelled)
|
||||
const isUploading = computed(() => summary.value.stage === 'uploading')
|
||||
const pendingTransfers = computed(() => summary.value.waiting + summary.value.uploading)
|
||||
const parseSettled = computed(() => summary.value.uploaded - summary.value.parsing)
|
||||
|
||||
watch(issueCount, count => {
|
||||
if (count === 0) filter.value = 'all'
|
||||
})
|
||||
|
||||
// ---- transfer rate ------------------------------------------------------
|
||||
|
||||
const samples: RateSample[] = []
|
||||
const rate = ref(0)
|
||||
let sampleTimer: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
const takeSample = () => {
|
||||
const bytes = summary.value.sentBytes
|
||||
const last = samples[samples.length - 1]
|
||||
// A failed, cancelled or retried transfer moves the count backwards; start over.
|
||||
if (last && bytes < last.bytes) samples.length = 0
|
||||
samples.push({ at: Date.now(), bytes })
|
||||
if (samples.length > 20) samples.shift()
|
||||
rate.value = estimateRate(samples)
|
||||
}
|
||||
|
||||
const stopSampling = () => {
|
||||
if (sampleTimer) clearInterval(sampleTimer)
|
||||
sampleTimer = null
|
||||
samples.length = 0
|
||||
rate.value = 0
|
||||
}
|
||||
|
||||
watch(isUploading, uploading => {
|
||||
if (uploading && !sampleTimer) {
|
||||
takeSample()
|
||||
sampleTimer = setInterval(takeSample, 1000)
|
||||
} else if (!uploading) {
|
||||
stopSampling()
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
const remainingText = computed(() => {
|
||||
const seconds = estimateRemainingSeconds(summary.value.totalBytes - summary.value.loadedBytes, rate.value)
|
||||
if (seconds === null) return ''
|
||||
const { unit, value } = splitDuration(seconds)
|
||||
return t('uploadTasks.remaining', { time: t(`uploadTasks.eta.${unit}`, { n: value }) })
|
||||
})
|
||||
|
||||
// ---- header -------------------------------------------------------------
|
||||
|
||||
const batchLabel = (batch: UploadBatch) =>
|
||||
batch.targetFolder ? `${batch.kbName} / ${batch.targetFolder}` : batch.kbName
|
||||
|
||||
const destination = computed(() => {
|
||||
const kbIds = new Set(batches.value.map(batch => batch.kbId))
|
||||
if (kbIds.size > 1) return t('uploadTasks.destinationMany', { count: kbIds.size })
|
||||
const batch = batches.value[0]
|
||||
if (!batch) return ''
|
||||
return t('uploadTasks.destination', { name: batchLabel(batch) })
|
||||
})
|
||||
|
||||
const headline = computed(() => {
|
||||
const s = summary.value
|
||||
if (s.stage === 'uploading') {
|
||||
return t('uploadTasks.titleUploading', { done: s.transferSettled, total: s.transferTotal })
|
||||
}
|
||||
if (s.stage === 'parsing') {
|
||||
return t('uploadTasks.titleParsing', { done: parseSettled.value, total: s.uploaded })
|
||||
}
|
||||
if (s.ready === 0 && s.failed + s.duplicate === 0) return t('uploadTasks.titleCancelled')
|
||||
if (issueCount.value === 0) return t('uploadTasks.titleDone')
|
||||
return t('uploadTasks.titleDoneWithIssues', { ok: s.ready, bad: issueCount.value })
|
||||
})
|
||||
|
||||
const subline = computed(() => {
|
||||
const s = summary.value
|
||||
if (s.stage !== 'uploading') return destination.value
|
||||
const transferred = `${formatFileSize(s.loadedBytes) || '0 B'} / ${formatFileSize(s.totalBytes) || '0 B'}`
|
||||
return remainingText.value ? `${transferred} · ${remainingText.value}` : transferred
|
||||
})
|
||||
|
||||
type BadgeTone = 'brand' | 'success' | 'warning' | 'neutral'
|
||||
|
||||
const badge = computed<{ tone: BadgeTone; icon: string; ring: number | null }>(() => {
|
||||
const s = summary.value
|
||||
if (s.stage === 'uploading') {
|
||||
return { tone: 'brand', icon: 'arrow-up', ring: s.totalBytes > 0 ? s.loadedBytes / s.totalBytes : 0 }
|
||||
}
|
||||
if (s.stage === 'parsing') {
|
||||
return { tone: 'brand', icon: 'file-search', ring: s.uploaded > 0 ? parseSettled.value / s.uploaded : 0 }
|
||||
}
|
||||
if (s.ready === 0 && s.failed + s.duplicate === 0) return { tone: 'neutral', icon: 'close', ring: null }
|
||||
if (issueCount.value > 0) return { tone: 'warning', icon: 'error', ring: null }
|
||||
return { tone: 'success', icon: 'check', ring: null }
|
||||
})
|
||||
|
||||
// ---- progress bar -------------------------------------------------------
|
||||
|
||||
const percent = (fraction: number) => `${(fraction * 100).toFixed(2)}%`
|
||||
|
||||
const overallPercent = computed(() => {
|
||||
const { bar } = summary.value
|
||||
return Math.round((bar.ready + bar.failed + bar.duplicate) * 100)
|
||||
})
|
||||
|
||||
const legend = computed(() => {
|
||||
const s = summary.value
|
||||
return [
|
||||
{ key: 'ready', label: t('uploadTasks.legend.ready'), count: s.ready },
|
||||
{ key: 'active', label: t('uploadTasks.legend.active'), count: s.uploading + s.parsing },
|
||||
{ key: 'waiting', label: t('uploadTasks.legend.waiting'), count: s.waiting },
|
||||
{ key: 'failed', label: t('uploadTasks.legend.failed'), count: s.failed },
|
||||
{ key: 'duplicate', label: t('uploadTasks.legend.duplicate'), count: s.duplicate },
|
||||
].filter(entry => entry.count > 0)
|
||||
})
|
||||
|
||||
const hint = computed(() => {
|
||||
if (summary.value.stage === 'uploading') return { icon: 'info-circle', text: t('uploadTasks.hintUploading') }
|
||||
if (summary.value.stage === 'parsing') return { icon: 'check-circle', text: t('uploadTasks.hintParsing') }
|
||||
return null
|
||||
})
|
||||
|
||||
// ---- list ---------------------------------------------------------------
|
||||
|
||||
const isIssue = (item: UploadItem) => {
|
||||
const phase = itemPhase(item)
|
||||
return phase === 'failed' || phase === 'duplicate' || phase === 'cancelled'
|
||||
}
|
||||
|
||||
const groups = computed(() => {
|
||||
const visibleItems = filter.value === 'issues' ? items.value.filter(isIssue) : items.value
|
||||
const byBatch = new Map<string, UploadItem[]>()
|
||||
for (const item of visibleItems) {
|
||||
if (!byBatch.has(item.batchId)) byBatch.set(item.batchId, [])
|
||||
byBatch.get(item.batchId)!.push(item)
|
||||
}
|
||||
return batches.value
|
||||
.filter(batch => byBatch.has(batch.id))
|
||||
.map(batch => ({ batch, label: batchLabel(batch), items: byBatch.get(batch.id)! }))
|
||||
})
|
||||
|
||||
const openItem = (item: UploadItem) => {
|
||||
const kbId = store.batchById.get(item.batchId)?.kbId
|
||||
if (!kbId || !item.knowledgeId) return
|
||||
// Same knowledge base page: vue-router dedupes an identical navigation, so
|
||||
// ask the page to open the document directly (as the command palette does).
|
||||
if (route.params.kbId === kbId) {
|
||||
window.dispatchEvent(new CustomEvent('weknora:open-knowledge', {
|
||||
detail: { kbId, knowledgeId: item.knowledgeId },
|
||||
}))
|
||||
return
|
||||
}
|
||||
router.push({ path: `/platform/knowledge-bases/${kbId}`, query: { knowledge_id: item.knowledgeId } })
|
||||
}
|
||||
|
||||
// ---- auto dismiss -------------------------------------------------------
|
||||
|
||||
let dismissTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
const finishedCleanly = computed(() => {
|
||||
const s = summary.value
|
||||
return s.stage === 'done' && s.ready > 0 && issueCount.value === 0
|
||||
})
|
||||
|
||||
watch([finishedCleanly, hovering], ([clean, hover]) => {
|
||||
if (dismissTimer) clearTimeout(dismissTimer)
|
||||
dismissTimer = null
|
||||
if (clean && !hover) dismissTimer = setTimeout(() => store.dismiss(), AUTO_DISMISS_MS)
|
||||
})
|
||||
|
||||
// ---- leaving the page ---------------------------------------------------
|
||||
|
||||
// Closing the tab kills in-flight requests; parsing is server side and survives.
|
||||
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
|
||||
if (!isUploading.value) return
|
||||
event.preventDefault()
|
||||
event.returnValue = ''
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener('beforeunload', handleBeforeUnload)
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('beforeunload', handleBeforeUnload)
|
||||
stopSampling()
|
||||
if (dismissTimer) clearTimeout(dismissTimer)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Transition name="upload-tasks-panel">
|
||||
<section
|
||||
v-if="visible && items.length > 0"
|
||||
class="upload-tasks-panel"
|
||||
role="region"
|
||||
:aria-label="t('uploadTasks.panelLabel')"
|
||||
@mouseenter="hovering = true"
|
||||
@mouseleave="hovering = false"
|
||||
>
|
||||
<header class="panel-header">
|
||||
<span class="panel-badge" :class="`is-${badge.tone}`" aria-hidden="true">
|
||||
<ProgressRing v-if="badge.ring !== null" class="panel-badge-ring" :value="badge.ring" :size="36" :stroke="2.5" />
|
||||
<t-icon :name="badge.icon" />
|
||||
</span>
|
||||
<div class="panel-heading">
|
||||
<div class="panel-title" aria-live="polite">{{ headline }}</div>
|
||||
<div class="panel-subtitle" :title="subline">{{ subline }}</div>
|
||||
</div>
|
||||
<div class="panel-header-actions">
|
||||
<t-button
|
||||
variant="text"
|
||||
shape="square"
|
||||
size="small"
|
||||
:aria-label="collapsed ? t('uploadTasks.expand') : t('uploadTasks.collapse')"
|
||||
:aria-expanded="!collapsed"
|
||||
@click="store.toggleCollapsed()"
|
||||
>
|
||||
<template #icon><t-icon :name="collapsed ? 'chevron-up' : 'chevron-down'" /></template>
|
||||
</t-button>
|
||||
<t-popconfirm
|
||||
v-if="isUploading"
|
||||
theme="warning"
|
||||
attach="body"
|
||||
placement="top-right"
|
||||
:content="t('uploadTasks.closeConfirm', { count: pendingTransfers })"
|
||||
:confirm-btn="{ content: t('uploadTasks.closeConfirmOk'), theme: 'danger' }"
|
||||
:cancel-btn="{ content: t('uploadTasks.closeConfirmKeep') }"
|
||||
@confirm="store.dismiss()"
|
||||
>
|
||||
<t-button variant="text" shape="square" size="small" :aria-label="t('uploadTasks.close')">
|
||||
<template #icon><t-icon name="close" /></template>
|
||||
</t-button>
|
||||
</t-popconfirm>
|
||||
<t-button
|
||||
v-else
|
||||
variant="text"
|
||||
shape="square"
|
||||
size="small"
|
||||
:aria-label="t('uploadTasks.close')"
|
||||
@click="store.dismiss()"
|
||||
>
|
||||
<template #icon><t-icon name="close" /></template>
|
||||
</t-button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="panel-progress">
|
||||
<div
|
||||
class="panel-bar"
|
||||
role="progressbar"
|
||||
aria-valuemin="0"
|
||||
aria-valuemax="100"
|
||||
:aria-valuenow="overallPercent"
|
||||
>
|
||||
<span class="bar-segment is-ready" :style="{ width: percent(summary.bar.ready) }" />
|
||||
<span class="bar-segment is-active" :style="{ width: percent(summary.bar.active) }" />
|
||||
<span class="bar-segment is-failed" :style="{ width: percent(summary.bar.failed) }" />
|
||||
<span class="bar-segment is-duplicate" :style="{ width: percent(summary.bar.duplicate) }" />
|
||||
</div>
|
||||
<ul v-if="!collapsed && legend.length > 0" class="panel-legend">
|
||||
<li v-for="entry in legend" :key="entry.key" :class="`is-${entry.key}`">
|
||||
<i aria-hidden="true" />{{ entry.label }}<b>{{ entry.count }}</b>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div v-if="!collapsed" class="panel-body">
|
||||
<p v-if="hint" class="panel-hint" :class="`is-${summary.stage}`">
|
||||
<t-icon :name="hint.icon" />
|
||||
<span>{{ hint.text }}</span>
|
||||
</p>
|
||||
|
||||
<div v-if="issueCount > 0 && items.length > 1" class="panel-filter" role="tablist">
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
:aria-selected="filter === 'all'"
|
||||
:class="{ 'is-active': filter === 'all' }"
|
||||
@click="filter = 'all'"
|
||||
>
|
||||
{{ t('uploadTasks.filterAll') }}<span>{{ items.length }}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
:aria-selected="filter === 'issues'"
|
||||
:class="{ 'is-active': filter === 'issues' }"
|
||||
@click="filter = 'issues'"
|
||||
>
|
||||
{{ t('uploadTasks.filterIssues') }}<span class="is-issue">{{ issueCount }}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="panel-list">
|
||||
<template v-for="group in groups" :key="group.batch.id">
|
||||
<div v-if="batches.length > 1" class="panel-group" :title="group.label">
|
||||
<span>{{ group.label }}</span>
|
||||
<span class="panel-group-count">{{ group.items.length }}</span>
|
||||
</div>
|
||||
<UploadTaskRow
|
||||
v-for="item in group.items"
|
||||
:key="item.id"
|
||||
:item="item"
|
||||
@cancel="store.cancelItem"
|
||||
@retry="store.retryItem"
|
||||
@open="openItem"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<footer v-if="isUploading || summary.retryable > 0" class="panel-footer">
|
||||
<t-button v-if="isUploading" variant="text" size="small" @click="store.cancelAll()">
|
||||
{{ t('uploadTasks.cancelAll') }}
|
||||
</t-button>
|
||||
<t-button
|
||||
v-if="summary.retryable > 0"
|
||||
class="panel-footer-retry"
|
||||
theme="primary"
|
||||
variant="text"
|
||||
size="small"
|
||||
@click="store.retryFailed()"
|
||||
>
|
||||
<template #icon><t-icon name="refresh" /></template>
|
||||
{{ t('uploadTasks.retryFailed', { count: summary.retryable }) }}
|
||||
</t-button>
|
||||
</footer>
|
||||
</div>
|
||||
</section>
|
||||
</Transition>
|
||||
</template>
|
||||
|
||||
<style scoped lang="less">
|
||||
.upload-tasks-panel {
|
||||
position: fixed;
|
||||
right: var(--app-space-6);
|
||||
bottom: var(--app-space-6);
|
||||
// Above page content, below modal shells and drawers.
|
||||
z-index: var(--z-dropdown);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 380px;
|
||||
max-width: calc(100vw - var(--app-space-8));
|
||||
max-height: calc(100vh - var(--app-space-10) * 2);
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: var(--app-radius-xl);
|
||||
background: var(--td-bg-color-container);
|
||||
box-shadow: var(--td-shadow-2);
|
||||
font-family: var(--app-font-family);
|
||||
|
||||
@media (max-width: 640px) {
|
||||
right: var(--app-space-4);
|
||||
bottom: var(--app-space-4);
|
||||
}
|
||||
}
|
||||
|
||||
.upload-tasks-panel-enter-active,
|
||||
.upload-tasks-panel-leave-active {
|
||||
transition: opacity var(--app-motion-slow) ease, transform var(--app-motion-slow) ease;
|
||||
}
|
||||
|
||||
.upload-tasks-panel-enter-from,
|
||||
.upload-tasks-panel-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(12px);
|
||||
}
|
||||
|
||||
// ---- header ---------------------------------------------------------------
|
||||
|
||||
.panel-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--app-space-3);
|
||||
padding: var(--app-space-4) var(--app-space-3) 0 var(--app-space-4);
|
||||
}
|
||||
|
||||
.panel-badge {
|
||||
position: relative;
|
||||
display: grid;
|
||||
flex-shrink: 0;
|
||||
place-items: center;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 50%;
|
||||
font-size: var(--app-text-xl);
|
||||
|
||||
&.is-brand,
|
||||
&.is-success {
|
||||
background: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
&.is-warning {
|
||||
background: color-mix(in srgb, var(--td-warning-color) 12%, transparent);
|
||||
color: var(--td-warning-color);
|
||||
}
|
||||
|
||||
&.is-neutral {
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
}
|
||||
|
||||
.panel-badge-ring {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
}
|
||||
|
||||
.panel-heading {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.panel-title {
|
||||
color: var(--td-text-color-primary);
|
||||
font-size: var(--app-text-base);
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-weight: 600;
|
||||
line-height: 22px;
|
||||
}
|
||||
|
||||
.panel-subtitle {
|
||||
overflow: hidden;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-sm);
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 18px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.panel-header-actions {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
align-self: flex-start;
|
||||
gap: 2px;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
// ---- progress -------------------------------------------------------------
|
||||
|
||||
.panel-progress {
|
||||
padding: var(--app-space-3) var(--app-space-4);
|
||||
}
|
||||
|
||||
.panel-bar {
|
||||
display: flex;
|
||||
height: 6px;
|
||||
overflow: hidden;
|
||||
border-radius: var(--app-radius-pill);
|
||||
background: var(--td-bg-color-component);
|
||||
}
|
||||
|
||||
.bar-segment {
|
||||
height: 100%;
|
||||
transition: width var(--app-motion-slow) ease;
|
||||
|
||||
&.is-ready {
|
||||
background: var(--td-brand-color);
|
||||
}
|
||||
|
||||
// Uploaded or uploading but not yet searchable: a moving sheen says "working".
|
||||
&.is-active {
|
||||
background-color: color-mix(in srgb, var(--td-brand-color) 32%, transparent);
|
||||
background-image: linear-gradient(
|
||||
90deg,
|
||||
transparent 0%,
|
||||
color-mix(in srgb, var(--td-brand-color) 38%, transparent) 50%,
|
||||
transparent 100%
|
||||
);
|
||||
background-size: 200% 100%;
|
||||
animation: bar-sheen 1.6s linear infinite;
|
||||
}
|
||||
|
||||
&.is-failed {
|
||||
background: var(--td-error-color);
|
||||
}
|
||||
|
||||
&.is-duplicate {
|
||||
background: var(--td-warning-color);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes bar-sheen {
|
||||
from {
|
||||
background-position: 100% 0;
|
||||
}
|
||||
|
||||
to {
|
||||
background-position: -100% 0;
|
||||
}
|
||||
}
|
||||
|
||||
.panel-legend {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--app-space-1) var(--app-space-3);
|
||||
margin: var(--app-space-2) 0 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 18px;
|
||||
|
||||
li {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--app-space-1);
|
||||
}
|
||||
|
||||
i {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
b {
|
||||
color: var(--td-text-color-primary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.is-ready i {
|
||||
background: var(--td-brand-color);
|
||||
}
|
||||
|
||||
.is-active i {
|
||||
background: color-mix(in srgb, var(--td-brand-color) 45%, transparent);
|
||||
}
|
||||
|
||||
.is-waiting i {
|
||||
background: var(--td-bg-color-component-active);
|
||||
}
|
||||
|
||||
.is-failed i {
|
||||
background: var(--td-error-color);
|
||||
}
|
||||
|
||||
.is-duplicate i {
|
||||
background: var(--td-warning-color);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- body -----------------------------------------------------------------
|
||||
|
||||
.panel-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
border-top: 1px solid var(--td-component-stroke);
|
||||
}
|
||||
|
||||
.panel-hint {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 6px;
|
||||
margin: var(--app-space-3) var(--app-space-4) 0;
|
||||
padding: var(--app-space-2) var(--app-space-3);
|
||||
border-radius: var(--app-radius-md);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 18px;
|
||||
|
||||
.t-icon {
|
||||
flex-shrink: 0;
|
||||
margin-top: 2px;
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-base);
|
||||
}
|
||||
|
||||
&.is-parsing {
|
||||
background: color-mix(in srgb, var(--td-brand-color) 8%, transparent);
|
||||
|
||||
.t-icon {
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.panel-filter {
|
||||
display: inline-flex;
|
||||
align-self: flex-start;
|
||||
gap: 2px;
|
||||
margin: var(--app-space-3) var(--app-space-4) 0;
|
||||
padding: 2px;
|
||||
border-radius: var(--app-radius-md);
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
|
||||
button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--app-space-1);
|
||||
padding: 2px var(--app-space-3);
|
||||
border: 0;
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: transparent;
|
||||
color: var(--td-text-color-secondary);
|
||||
font: inherit;
|
||||
font-size: var(--app-text-sm);
|
||||
line-height: 20px;
|
||||
cursor: pointer;
|
||||
transition: background-color var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
|
||||
|
||||
&:hover {
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
&.is-active {
|
||||
background: var(--td-bg-color-container);
|
||||
color: var(--td-text-color-primary);
|
||||
box-shadow: var(--td-shadow-1);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--td-brand-color);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
}
|
||||
|
||||
span {
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-variant-numeric: tabular-nums;
|
||||
|
||||
&.is-issue {
|
||||
color: var(--td-error-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.panel-list {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
max-height: 300px;
|
||||
padding: var(--app-space-2);
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
|
||||
.panel-group {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--app-space-2);
|
||||
padding: var(--app-space-2) var(--app-space-2) var(--app-space-1);
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: var(--app-text-sm);
|
||||
font-weight: 500;
|
||||
|
||||
span:first-child {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.panel-group-count {
|
||||
flex-shrink: 0;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.panel-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: var(--app-space-2) var(--app-space-3);
|
||||
border-top: 1px solid var(--td-component-stroke);
|
||||
}
|
||||
|
||||
.panel-footer-retry {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.bar-segment.is-active {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.upload-tasks-panel-enter-active,
|
||||
.upload-tasks-panel-leave-active,
|
||||
.bar-segment {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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'
|
||||
|
|
|
|||
|
|
@ -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: '推奨モデル'
|
||||
|
|
|
|||
|
|
@ -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: {
|
||||
|
|
|
|||
|
|
@ -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: {
|
||||
|
|
|
|||
|
|
@ -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: {
|
||||
|
|
|
|||
|
|
@ -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<UploadQueueDeps> = {}) {
|
||||
const items: UploadItem[] = []
|
||||
const batches: UploadBatch[] = []
|
||||
const calls: Call[] = []
|
||||
const ends: Array<[string, TransferEnd]> = []
|
||||
const statusRows = new Map<string, KnowledgeStatusRow[] | null>()
|
||||
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)
|
||||
})
|
||||
|
|
@ -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<typeof setTimeout>),
|
||||
}
|
||||
|
||||
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<unknown>
|
||||
/** Current rows for the ids, or null when the request failed. */
|
||||
queryStatus: (kbId: string, knowledgeIds: string[]) => Promise<KnowledgeStatusRow[] | null>
|
||||
/** 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<string, UploadPayload>()
|
||||
const controllers = new Map<string, AbortController>()
|
||||
const missingPolls = new Map<string, number>()
|
||||
// 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<UploadBatch, 'id'>, 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<string, UploadItem[]>()
|
||||
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<void>[] = []
|
||||
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<string, unknown>()
|
||||
const pending = new Set<string>()
|
||||
const finals = new Map<string, unknown>()
|
||||
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
|
@ -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],
|
||||
})
|
||||
})
|
||||
|
|
@ -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)
|
||||
})
|
||||
|
|
@ -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<unknown>[]
|
||||
timers?: Timers
|
||||
}
|
||||
|
||||
export function createUploadTasks(deps: UploadTasksDeps) {
|
||||
const items = reactive<UploadItem[]>([])
|
||||
const batches = reactive<UploadBatch[]>([])
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
|
@ -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> = {}): 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 })
|
||||
})
|
||||
|
|
@ -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<T extends UploadItem>(
|
||||
items: readonly T[],
|
||||
concurrency: number,
|
||||
conflictKey?: (item: T) => string,
|
||||
): T[] {
|
||||
let running = 0
|
||||
const busyKeys = new Set<string>()
|
||||
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 }
|
||||
}
|
||||
|
|
@ -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<any>(null);
|
||||
const uploadSourceRef = ref<InstanceType<typeof KbUploadSourceDropdown> | 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,
|
||||
|
|
|
|||
|
|
@ -32,44 +32,6 @@
|
|||
<span>{{ $t('knowledgeList.uninitializedBanner') }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 上传进度提示 -->
|
||||
<div v-if="uploadSummaries.length" class="upload-progress-panel">
|
||||
<div v-for="summary in uploadSummaries" :key="summary.kbId" class="upload-progress-item">
|
||||
<div class="upload-progress-icon">
|
||||
<t-icon :name="summary.completed === summary.total ? 'check-circle-filled' : 'upload'" size="20px" />
|
||||
</div>
|
||||
<div class="upload-progress-content">
|
||||
<div class="progress-title">
|
||||
{{
|
||||
summary.completed === summary.total
|
||||
? $t('knowledgeList.uploadProgress.completedTitle', { name: summary.kbName })
|
||||
: $t('knowledgeList.uploadProgress.uploadingTitle', { name: summary.kbName })
|
||||
}}
|
||||
</div>
|
||||
<div class="progress-subtitle">
|
||||
{{
|
||||
summary.completed === summary.total
|
||||
? $t('knowledgeList.uploadProgress.completedDetail', { total: summary.total })
|
||||
: $t('knowledgeList.uploadProgress.detail', { completed: summary.completed, total: summary.total })
|
||||
}}
|
||||
</div>
|
||||
<div class="progress-subtitle secondary">
|
||||
{{
|
||||
summary.completed === summary.total
|
||||
? $t('knowledgeList.uploadProgress.refreshing')
|
||||
: $t('knowledgeList.uploadProgress.keepPageOpen')
|
||||
}}
|
||||
</div>
|
||||
<div v-if="summary.hasError" class="progress-subtitle error">
|
||||
{{ $t('knowledgeList.uploadProgress.errorTip') }}
|
||||
</div>
|
||||
<div class="progress-bar">
|
||||
<div class="progress-bar-inner" :style="{ width: summary.progress + '%' }"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 骨架屏占位 -->
|
||||
<div v-if="loading && kbs.length === 0" class="kb-card-wrap">
|
||||
<div v-for="n in 6" :key="'skel-' + n" class="kb-card kb-card-skeleton is-skeleton">
|
||||
|
|
@ -843,10 +805,7 @@ const confirmDelete = useConfirmDelete()
|
|||
const currentMoreIndex = ref<number>(-1)
|
||||
const highlightedKbId = ref<string | null>(null)
|
||||
const highlightedCardRef = ref<HTMLElement | null>(null)
|
||||
const uploadTasks = ref<UploadTaskState[]>([])
|
||||
const uploadCleanupTimers = new Map<string, ReturnType<typeof setTimeout>>()
|
||||
let uploadRefreshTimer: ReturnType<typeof setTimeout> | 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<UploadSummary[]>(() => {
|
||||
if (!uploadTasks.value.length) return []
|
||||
const grouped: Record<string, UploadTaskState[]> = {}
|
||||
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<UploadTaskState>) => {
|
||||
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<UploadEventDetail>).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<UploadEventDetail>).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<UploadEventDetail>).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;
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@
|
|||
<!-- 全局右上角"待处理邀请"铃铛。固定定位,z-index 低于抽屉,业务页面
|
||||
右侧抽屉弹出时会自然覆盖;仅在有待处理邀请时渲染。 -->
|
||||
<GlobalInvitationBell />
|
||||
<!-- 知识库文件上传进度浮层:上传队列放在 store 里,切换页面不中断 -->
|
||||
<UploadTasksPanel />
|
||||
<!-- 带遮罩层的新手引导:首次进入自动开启,可从用户菜单顶部昵称旁帮助按钮重新打开 -->
|
||||
<NewUserGuide />
|
||||
</div>
|
||||
|
|
@ -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'
|
||||
|
|
|
|||
Loading…
Reference in New Issue