From 988ae2429dd4c507c712599151cc361e4b235332 Mon Sep 17 00:00:00 2001 From: Orion Date: Fri, 18 Sep 2026 15:38:44 +0800 Subject: [PATCH 01/10] =?UTF-8?q?=F0=9F=90=9B=20fix(frontend):=20=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=E4=B8=8A=E4=BC=A0=E8=BF=9B=E5=BA=A6=E4=B8=8E=E5=8F=96?= =?UTF-8?q?=E4=BB=B6=E8=AF=A6=E6=83=85=E5=BC=B9=E7=AA=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/common/FileDetailModal.vue | 138 ++++------------------ src/composables/useSendFlow.ts | 10 +- src/composables/useSendSubmit.ts | 6 +- src/services/upload-strategy.ts | 11 +- src/types/file.ts | 2 + 5 files changed, 43 insertions(+), 124 deletions(-) diff --git a/src/components/common/FileDetailModal.vue b/src/components/common/FileDetailModal.vue index 8d1f5b9..878624a 100644 --- a/src/components/common/FileDetailModal.vue +++ b/src/components/common/FileDetailModal.vue @@ -1,110 +1,26 @@ - - diff --git a/src/composables/useSendFlow.ts b/src/composables/useSendFlow.ts index d3dad78..281021f 100644 --- a/src/composables/useSendFlow.ts +++ b/src/composables/useSendFlow.ts @@ -27,6 +27,8 @@ export function useSendFlow() { const expirationMethod = ref(config.value.expireStyle[0] || 'day') const expirationValue = ref('1') const uploadProgress = ref(0) + const uploadedBytes = ref(0) + const totalBytes = ref(0) const showDrawer = ref(false) const selectedRecord = ref(null) const isSubmitting = ref(false) @@ -62,7 +64,9 @@ export function useSendFlow() { notify: (message, type) => alertStore.showAlert(message, type), translate: t, onProgress: (progress) => { - uploadProgress.value = progress + uploadProgress.value = progress.percentage + uploadedBytes.value = progress.loaded + totalBytes.value = progress.total }, onFinalizing: () => { isFinalizing.value = true }, onHashCalculated: (hash) => { @@ -285,6 +289,8 @@ export function useSendFlow() { alertStore.showAlert(getErrorMessage(error, t('send.messages.sendFailed')), 'error') } finally { uploadProgress.value = 0 + uploadedBytes.value = 0 + totalBytes.value = 0 isSubmitting.value = false isFinalizing.value = false } @@ -319,6 +325,8 @@ export function useSendFlow() { expirationMethod, expirationValue, uploadProgress, + uploadedBytes, + totalBytes, showDrawer, selectedRecord, isSubmitting, diff --git a/src/composables/useSendSubmit.ts b/src/composables/useSendSubmit.ts index 442778b..59a59ba 100644 --- a/src/composables/useSendSubmit.ts +++ b/src/composables/useSendSubmit.ts @@ -12,7 +12,7 @@ type UseSendSubmitOptions = { getMaxFileSize: () => number notify: (message: string, type: AlertType) => void translate: Translate - onProgress: (progress: number) => void + onProgress: (progress: UploadProgress) => void onFinalizing: () => void onHashCalculated: (hash: string) => void } @@ -49,7 +49,7 @@ export function useSendSubmit(options: UseSendSubmitOptions) { onHashCalculated: options.onHashCalculated, onFinalizing: options.onFinalizing, onProgress: (progress: UploadProgress) => { - options.onProgress(progress.percentage) + options.onProgress(progress) }, messages: { initFailed: options.translate('send.messages.initChunkUploadFailed'), @@ -68,7 +68,7 @@ export function useSendSubmit(options: UseSendSubmitOptions) { expireValue, expireStyle: expireStyle as ExpireStyle, onProgress: (progress) => { - options.onProgress(progress.percentage) + options.onProgress(progress) } }) diff --git a/src/services/upload-strategy.ts b/src/services/upload-strategy.ts index 2345dfa..d19004e 100644 --- a/src/services/upload-strategy.ts +++ b/src/services/upload-strategy.ts @@ -3,7 +3,7 @@ import { waitForUploadCompletion, isTransientCompletionError } from './upload-co import type { ApiResponse, ChunkUploadInitResponse, FileUploadResponse, UploadProgress } from '@/types' import { calculateFileHash } from '@/utils/file-processing' -const CHUNK_SIZE = 5 * 1024 * 1024 +export const CHUNK_SIZE = 100 * 1024 * 1024 type ChunkedUploadOptions = { expireValue: number @@ -26,6 +26,7 @@ const pendingCompletion = new WeakMap> { const session = pendingCompletion.get(file)! + options.onProgress?.({loaded:file.size,total:file.size,percentage:99}) options.onFinalizing?.() try { const response = await waitForUploadCompletion(() => FileService.completeChunkUpload(session.uploadId, { @@ -55,7 +56,6 @@ export const uploadChunkedFile = async ( const fileHash = await calculateFileHash(file) options.onHashCalculated?.(fileHash) - const chunks = Math.ceil(file.size / CHUNK_SIZE) const initResponse = await FileService.initChunkUpload({ file_name: file.name, file_size: file.size, @@ -77,13 +77,16 @@ export const uploadChunkedFile = async ( throw new Error(options.messages?.initFailed || 'Init chunk upload failed') } + const chunkSize = initDetail.chunk_size || CHUNK_SIZE + const chunks = Math.ceil(file.size / chunkSize) const uploadedChunks = new Set(initDetail.uploaded_chunks || []) + options.onProgress?.({loaded:calculateCompletedBytes(uploadedChunks,chunkSize,file.size),total:file.size,percentage:0}) for (let index = 0; index < chunks; index++) { if (uploadedChunks.has(index)) { continue } - const start = index * CHUNK_SIZE + const start = index * chunkSize const end = Math.min(start + CHUNK_SIZE, file.size) const chunk = file.slice(start, end) const chunkResponse = await FileService.uploadChunk( @@ -91,7 +94,7 @@ export const uploadChunkedFile = async ( index, new Blob([chunk], { type: file.type }), (progress) => { - const completedBytes = calculateCompletedBytes(uploadedChunks, CHUNK_SIZE, file.size) + const completedBytes = calculateCompletedBytes(uploadedChunks, chunkSize, file.size) const percentage = Math.round(((completedBytes + progress.loaded) * 100) / file.size) options.onProgress?.({ loaded: completedBytes + progress.loaded, diff --git a/src/types/file.ts b/src/types/file.ts index ddc4fd5..2743f62 100644 --- a/src/types/file.ts +++ b/src/types/file.ts @@ -481,6 +481,8 @@ export interface ChunkUploadInitRequest { } export interface ChunkUploadInitResponse { + chunk_size?: number + total_chunks?: number code?: string name?: string upload_id?: string From 7c6119b0c9154461fadeb2a1cac42b2013c13743 Mon Sep 17 00:00:00 2001 From: Orion Date: Fri, 18 Sep 2026 16:02:49 +0800 Subject: [PATCH 02/10] =?UTF-8?q?=F0=9F=90=9B=20fix(frontend):=20=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=E4=B8=8A=E4=BC=A0=E8=BF=9B=E5=BA=A6=E4=B8=8E=E5=85=AB?= =?UTF-8?q?=E4=BD=8D=E5=8F=96=E4=BB=B6=E7=A0=81=E8=BE=93=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/common/RetrieveForm.vue | 6 +++--- src/composables/useRetrieveFlow.ts | 2 +- src/services/upload-strategy.ts | 2 +- src/views/RetrievewFileView.vue | 2 +- src/views/SendFileView.vue | 4 ++++ tests/fixtures/browser-save.stub.mjs | 1 + tests/transferUi.integration.test.mjs | 18 ++++++++++++++++++ 7 files changed, 29 insertions(+), 6 deletions(-) create mode 100644 tests/fixtures/browser-save.stub.mjs create mode 100644 tests/transferUi.integration.test.mjs diff --git a/src/components/common/RetrieveForm.vue b/src/components/common/RetrieveForm.vue index ed44856..4d09880 100644 --- a/src/components/common/RetrieveForm.vue +++ b/src/components/common/RetrieveForm.vue @@ -25,7 +25,7 @@ required :aria-invalid="error" :readonly="inputStatus.readonly" - maxlength="5" + maxlength="8" @focus="isInputFocused = true" @blur="isInputFocused = false" /> @@ -46,7 +46,7 @@ + +

正在停止传输并清理临时文件,请稍候。

+

{{ submitMessage }}

@@ -168,6 +175,7 @@ const { showDrawer, selectedRecord, isSubmitting, + isCancelling, cleanupPending, submitMessage, cancelUpload, isFinalizing, sendRecords, uploadDescription, diff --git a/src/views/manage/FileManageView.vue b/src/views/manage/FileManageView.vue index d63fbcd..2edbc89 100644 --- a/src/views/manage/FileManageView.vue +++ b/src/views/manage/FileManageView.vue @@ -1704,6 +1704,7 @@ diff --git a/src/composables/index.ts b/src/composables/index.ts index 7828930..e3edf88 100644 --- a/src/composables/index.ts +++ b/src/composables/index.ts @@ -16,3 +16,5 @@ export { useTheme } from './useTheme' export { useTransferAnalytics } from './useTransferAnalytics' export { useLocalFiles } from './useLocalFiles' + +export { useDownloadChecks } from './useDownloadChecks' diff --git a/src/composables/useAdminFiles.ts b/src/composables/useAdminFiles.ts index 059c061..5b970c6 100644 --- a/src/composables/useAdminFiles.ts +++ b/src/composables/useAdminFiles.ts @@ -651,7 +651,7 @@ export function useAdminFiles() { if (numericValue !== null) return t('fileManage.remaining', { count: numericValue }) } - if ((item.key === 'retrieved' || item.key === 'retrieved_event') && hasNumericTimelineValue(item)) { + if ((item.key === 'retrieved' || item.key === 'retrieved_event' || item.key === 'queried_event') && hasNumericTimelineValue(item)) { return `${normalizeTimelineNumber(item.value)} ${t('common.times')}` } @@ -673,7 +673,7 @@ export function useAdminFiles() { } const formatTimelineTitleValue = (item: AdminFileDetailTimelineItem, valueText: string) => { - if (item.key === 'retrieved_event') { + if (item.key === 'retrieved_event' || item.key === 'queried_event') { const numericValue = normalizeTimelineNumber(item.value) return numericValue === null ? '' : String(numericValue) } diff --git a/src/composables/useDownloadChecks.ts b/src/composables/useDownloadChecks.ts new file mode 100644 index 0000000..8130faf --- /dev/null +++ b/src/composables/useDownloadChecks.ts @@ -0,0 +1,90 @@ +import { onScopeDispose, ref, watch, type Ref } from 'vue' +import { DownloadCheckService, ConfigService } from '@/services' +import type { DownloadCheck } from '@/types/download-check' + +export function useDownloadChecks(files: Ref<{ id: number }[]>) { + const checks = ref>({}) + const interval = ref(300) + const saving = ref(false) + const error = ref('') + const checking = ref(false) + let controller: AbortController | undefined + let timer: ReturnType | undefined + let disposed = false + + const statusFor = (id: number): DownloadCheck => checks.value[id] ?? { + id, status: 'unknown', message: '尚未检测', checkedAt: null + } + const schedule = () => { + clearTimeout(timer) + if (!disposed && interval.value > 0) timer = setTimeout(() => { + if (typeof document !== 'undefined' && document.hidden) schedule() + else void refresh() + }, interval.value * 1000) + } + const refresh = async () => { + controller?.abort() + const current = new AbortController() + controller = current + clearTimeout(timer) + checking.value = true + const ids = files.value.map(file => file.id) + checks.value = Object.fromEntries(ids.map(id => [id, { + ...statusFor(id), status: 'checking', message: '正在检测' + }])) + try { + for (let offset = 0; offset < ids.length; offset += 20) { + const batch = ids.slice(offset, offset + 20) + try { + const response = await DownloadCheckService.check(batch, current.signal) + if (current.signal.aborted || disposed) return + if (response.code !== 200 || !Array.isArray(response.detail)) throw new Error('检测请求失败') + for (const id of batch) { + checks.value[id] = response.detail.find(item => item.id === id) ?? { + id, status: 'unknown', message: '未返回检测结果,请重试', checkedAt: null + } + } + } catch { + if (current.signal.aborted || disposed) return + for (const id of batch) checks.value[id] = { + id, status: 'unknown', message: '检测请求失败,请刷新重试', checkedAt: null + } + } + } + } finally { + if (controller === current && !disposed) { + checking.value = false + schedule() + } + } + } + const loadInterval = async () => { + try { + const response = await ConfigService.getConfig() + if (!disposed && response.code === 200) { + interval.value = response.detail?.downloadCheckInterval ?? 300 + schedule() + } + } catch { error.value = '无法读取检测间隔,暂按 5 分钟刷新' } + } + const saveInterval = async (value: number) => { + if (saving.value) return + saving.value = true + error.value = '' + try { + const response = await ConfigService.updateConfig({ downloadCheckInterval: value }) + if (response.code !== 200) throw new Error('save failed') + interval.value = value + schedule() + } catch { error.value = '检测间隔保存失败,请重试' } + finally { saving.value = false } + } + // Every successful list load (refresh, page, filter, or edit) gets fresh results. + watch(files, () => { void refresh() }) + onScopeDispose(() => { + disposed = true + controller?.abort() + clearTimeout(timer) + }) + return { checks, interval, saving, error, checking, statusFor, refresh, loadInterval, saveInterval } +} diff --git a/src/composables/useRetrieveFlow.ts b/src/composables/useRetrieveFlow.ts index fe827b0..d7a120f 100644 --- a/src/composables/useRetrieveFlow.ts +++ b/src/composables/useRetrieveFlow.ts @@ -9,6 +9,7 @@ import { copyToClipboard } from '@/utils/clipboard' import { getErrorMessage } from '@/utils/common' import { renderMarkdownPreview } from '@/utils/content-preview' import { downloadReceivedRecord } from '@/utils/download-action' +import { markRecordRetrieved } from '@/utils/receive-record' type InputStatus = { readonly: boolean @@ -60,8 +61,9 @@ export function useRetrieveFlow() { ? detail.type === 'text' : detail.name === 'Text' && !detail.text.startsWith('/share/download') const content = isText ? (detail.content ?? detail.text) : null - const downloadUrl = isText ? null : (detail.download_url ?? detail.text) + const downloadUrl = detail.download_url ?? (isText ? null : detail.text) + const queriedAt = new Date().toISOString() return { id: Date.now(), code: detail.code, @@ -69,7 +71,9 @@ export function useRetrieveFlow() { size: formatFileSize(detail.size), downloadUrl, content, - date: new Date().toLocaleString(), + date: queriedAt, + queriedAt, + retrievedAt: null, type: isText ? 'text' : 'file', remainingDownloads: detail.remaining_downloads } @@ -130,6 +134,7 @@ export function useRetrieveFlow() { (file) => file.code === newFileData.code ) if (existingIndex !== -1) { + newFileData.retrievedAt = fileStore.receiveData[existingIndex].retrievedAt ?? null fileStore.deleteReceiveData(existingIndex) } fileStore.addReceiveData(newFileData) @@ -186,7 +191,9 @@ export function useRetrieveFlow() { } const downloadRecord = (record: ReceivedFileRecord) => { - downloadReceivedRecord(record) + if (downloadReceivedRecord(record)) { + markRecordRetrieved(record) + } } const showContentPreview = () => { diff --git a/src/directives/resizable-columns.ts b/src/directives/resizable-columns.ts new file mode 100644 index 0000000..d3afcc0 --- /dev/null +++ b/src/directives/resizable-columns.ts @@ -0,0 +1,114 @@ +import type { ObjectDirective } from 'vue' +import { resizeColumn } from '../utils/column-width' +import '../assets/style/resizable-columns.css' + +const states = new WeakMap void; signature: () => boolean }>() + +function mount(table: HTMLTableElement) { + const view = table.ownerDocument.defaultView! + const headers = Array.from(table.querySelectorAll('thead th')) + const labels = headers.map(header => header.textContent?.trim() || '') + const handles: HTMLElement[] = [] + let stopDrag = () => {} + table.classList.add('resizable-columns') + + function measure() { + return headers.map(header => header.getBoundingClientRect().width) + } + + function minimum(header: HTMLTableCellElement) { + const range = table.ownerDocument.createRange() + range.selectNodeContents(header) + // Keep the label and padding visible even when the data column is narrowed. + const labelWidth = Array.from(range.getClientRects()).reduce((max, rect) => Math.max(max, rect.width), 0) + const style = view.getComputedStyle(header) + return Math.ceil(Math.max(72, labelWidth + parseFloat(style.paddingLeft) + parseFloat(style.paddingRight))) + } + + function apply(widths: number[]) { + table.style.tableLayout = 'fixed' + table.style.minWidth = '0' + table.style.width = `${widths.reduce((sum, width) => sum + width, 0)}px` + table.classList.add('columns-sized') + headers.forEach((header, index) => { + header.style.width = `${widths[index]}px` + handles[index]!.setAttribute('aria-valuenow', String(Math.round(widths[index]!))) + }) + } + + headers.forEach((header, index) => { + const handle = table.ownerDocument.createElement('span') + handle.className = 'column-resize-handle' + handle.tabIndex = 0 + handle.setAttribute('role', 'separator') + handle.setAttribute('aria-orientation', 'vertical') + header.setAttribute('aria-label', labels[index]!) + handle.setAttribute('aria-label', `${labels[index]} — ↔`) + handle.setAttribute('aria-valuenow', String(Math.round(header.getBoundingClientRect().width))) + header.append(handle) + handles.push(handle) + + handle.onpointerdown = event => { + if (event.button !== 0) return + event.preventDefault() + event.stopPropagation() + stopDrag() + const widths = measure() + const min = minimum(header) + const startX = event.clientX + const pointerId = event.pointerId + handle.setPointerCapture(pointerId) + table.classList.add('columns-resizing') + const move = (event: PointerEvent) => { + if (event.pointerId === pointerId) apply(resizeColumn(widths, index, event.clientX - startX, min)) + } + const finish = (event: PointerEvent) => { + if (event.pointerId === pointerId) stopDrag() + } + stopDrag = () => { + view.removeEventListener('pointermove', move) + view.removeEventListener('pointerup', finish) + view.removeEventListener('pointercancel', finish) + view.removeEventListener('blur', stopDrag) + handle.removeEventListener('lostpointercapture', finish) + if (handle.hasPointerCapture(pointerId)) handle.releasePointerCapture(pointerId) + table.classList.remove('columns-resizing') + stopDrag = () => {} + } + view.addEventListener('pointermove', move) + view.addEventListener('pointerup', finish) + view.addEventListener('pointercancel', finish) + view.addEventListener('blur', stopDrag) + handle.addEventListener('lostpointercapture', finish) + } + handle.onkeydown = event => { + if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return + event.preventDefault() + apply(resizeColumn(measure(), index, event.key === 'ArrowRight' ? 16 : -16, minimum(header))) + } + }) + states.set(table, { signature: () => { + const current = Array.from(table.querySelectorAll('thead th')) + return current.length === headers.length && current.every((header, index) => + header === headers[index] && header.textContent?.trim() === labels[index] && handles[index]?.isConnected) + }, cleanup: () => { + stopDrag() + handles.forEach(handle => handle.remove()) + headers.forEach(header => header.removeAttribute('aria-label')) + } }) +} + +export const vResizableColumns: ObjectDirective = { + mounted: mount, + updated(table) { + const state = states.get(table) + if (!state?.signature()) { + state?.cleanup() + mount(table) + } + }, + beforeUnmount(table) { + states.get(table)?.cleanup() + states.delete(table) + } +} diff --git a/src/i18n/locales/en-US.ts b/src/i18n/locales/en-US.ts index cfee306..12fdb65 100644 --- a/src/i18n/locales/en-US.ts +++ b/src/i18n/locales/en-US.ts @@ -406,7 +406,11 @@ export default { fileRecord: { filename: 'Filename', size: 'Size', - date: 'Date', + date: 'Lookup time', + queryTime: 'Lookup time', + retrieveTime: 'Retrieval time', + notRetrieved: 'Not retrieved yet', + retrieveTimeHint: 'Most recent download click; does not indicate completion.', code: 'Code', actions: 'Actions', download: 'Download', @@ -666,13 +670,17 @@ export default { title: 'Retrieval History', description: 'Retrieved {value}; current status is {status}.' }, + queried_event: { + title: 'Lookup #{value}', + description: 'Lookup succeeded. Source IP: {detail}.' + }, retrieved_event: { title: 'Retrieval #{value}', - description: 'This retrieval is complete; current status is {status}.' + description: 'Retrieval started; this does not indicate download completion.' }, retrieved_event_unknown: { title: 'Retrieval History', - description: 'This retrieval is complete; current status is {status}.' + description: 'Retrieval started; this does not indicate download completion.' } }, headers: { diff --git a/src/i18n/locales/zh-CN.ts b/src/i18n/locales/zh-CN.ts index 1160fd9..9c71024 100644 --- a/src/i18n/locales/zh-CN.ts +++ b/src/i18n/locales/zh-CN.ts @@ -581,7 +581,7 @@ export default { lifecycle: '生命周期', expandLifecycle: '展开全部生命周期记录(共 {count} 条)', collapseLifecycle: '收起生命周期记录', - expandRetrievalHistory: '展开全部取件记录(共 {count} 次)', + expandRetrievalHistory: '展开全部取件记录(共 {count} 条)', collapseRetrievalHistory: '收起取件记录', permanent: '永久有效', createdAt: '创建时间', @@ -662,13 +662,17 @@ export default { title: '取件记录', description: '累计取件 {value},当前状态为 {status}。' }, + queried_event: { + title: '第 {value} 次查件', + description: '查件成功,来源 IP:{detail}。' + }, retrieved_event: { title: '第 {value} 次取件', - description: '本次取件已完成,当前状态为 {status}。' + description: '已发起取件,不代表下载完成。' }, retrieved_event_unknown: { title: '取件记录', - description: '本次取件已完成,当前状态为 {status}。' + description: '已发起取件,不代表下载完成。' } }, headers: { @@ -709,7 +713,11 @@ export default { fileRecord: { filename: '文件名', size: '文件大小', - date: '取件日期', + date: '查件时间', + queryTime: '查件时间', + retrieveTime: '取件时间', + notRetrieved: '尚未取件', + retrieveTimeHint: '最近一次点击下载的时间,不代表下载完成。', code: '取件码', actions: '操作', download: '下载', diff --git a/src/services/download-check.ts b/src/services/download-check.ts new file mode 100644 index 0000000..c4ed481 --- /dev/null +++ b/src/services/download-check.ts @@ -0,0 +1,9 @@ +import api from './client' +import type { ApiResponse } from '@/types' +import type { DownloadCheck } from '@/types/download-check' + +export const DownloadCheckService = { + check(ids: number[], signal?: AbortSignal): Promise> { + return api.post('/admin/file/download-check', { ids }, { signal, timeout: 70000 }) + } +} diff --git a/src/services/index.ts b/src/services/index.ts index 0374385..77a602f 100644 --- a/src/services/index.ts +++ b/src/services/index.ts @@ -11,3 +11,5 @@ export { uploadChunkedFile } from './upload-strategy' export { LocalShareService } from './local-share' export { UploadCancellation, UploadInterrupted, isUploadInterrupted } from './upload-cancellation' + +export { DownloadCheckService } from './download-check' diff --git a/src/types/config.ts b/src/types/config.ts index aff2fbf..07899fa 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -47,6 +47,7 @@ export interface ConfigState { opacity: number enableChunk: number chunkSizeMB: number + downloadCheckInterval?: number s3_access_key_id: string background: string showAdminAddr: number diff --git a/src/types/download-check.ts b/src/types/download-check.ts new file mode 100644 index 0000000..0ba0c94 --- /dev/null +++ b/src/types/download-check.ts @@ -0,0 +1,6 @@ +export interface DownloadCheck { + id: number + status: 'available' | 'unavailable' | 'unknown' | 'checking' + message: string + checkedAt: string | null +} diff --git a/src/types/file.ts b/src/types/file.ts index 2743f62..ccdbf12 100644 --- a/src/types/file.ts +++ b/src/types/file.ts @@ -453,7 +453,10 @@ export interface ReceivedFileRecord { size: string downloadUrl: string | null content: string | null + /** Legacy query time, retained for existing records. */ date: string + queriedAt?: string + retrievedAt?: string | null type?: 'file' | 'text' remainingDownloads?: number | null } diff --git a/src/utils/column-width.ts b/src/utils/column-width.ts new file mode 100644 index 0000000..28391c6 --- /dev/null +++ b/src/utils/column-width.ts @@ -0,0 +1,3 @@ +export function resizeColumn(widths: number[], index: number, delta: number, minimum: number): number[] { + return widths.map((width, column) => column === index ? Math.max(minimum, width + delta) : width) +} diff --git a/src/utils/download-action.ts b/src/utils/download-action.ts index b3a4aa5..c461353 100644 --- a/src/utils/download-action.ts +++ b/src/utils/download-action.ts @@ -7,16 +7,18 @@ const unsafeFilenamePattern = new RegExp( 'g' ) -export function downloadReceivedRecord(record: ReceivedFileRecord): void { +export function downloadReceivedRecord(record: ReceivedFileRecord): boolean { if (record.downloadUrl) { window.open(buildDownloadUrl(record.downloadUrl), '_blank') - return + return true } - if (record.content) { + if (typeof record.content === 'string') { const blob = new Blob([record.content], { type: 'text/plain;charset=utf-8' }) saveAs(blob, `${record.filename}.txt`) + return true } + return false } export const getSafeFilename = (name: string) => diff --git a/src/utils/receive-record.ts b/src/utils/receive-record.ts new file mode 100644 index 0000000..650c002 --- /dev/null +++ b/src/utils/receive-record.ts @@ -0,0 +1,18 @@ +import type { ReceivedFileRecord } from '../types/file' + +/** Legacy date was written on lookup, never on download. */ +export function queriedAt(record: ReceivedFileRecord): string { + return record.queriedAt || record.date +} + +export function formatRecordTime(value?: string | null): string { + if (!value) return '' + // Old records contain locale-formatted dates; retain them without guessing. + if (!/^\d{4}-\d{2}-\d{2}T/.test(value)) return value + const time = new Date(value) + return Number.isNaN(time.getTime()) ? value : time.toLocaleString() +} + +export function markRecordRetrieved(record: ReceivedFileRecord, at = new Date()): void { + record.retrievedAt = at.toISOString() +} diff --git a/src/views/RetrievewFileView.vue b/src/views/RetrievewFileView.vue index 19b65ca..97df86a 100644 --- a/src/views/RetrievewFileView.vue +++ b/src/views/RetrievewFileView.vue @@ -44,6 +44,7 @@ :record="selectedRecord" @close="closeDetails" @preview-content="showContentPreview" + @download-record="downloadRecord" />
{{ t('admin.dashboard.topDownloads.file') }} {{ t('admin.dashboard.topDownloads.downloads') }} {{ t('admin.dashboard.topDownloads.traffic') }} {{ t('admin.dashboard.topDownloads.status') }} @@ -417,6 +418,7 @@ + + diff --git a/tests/README.md b/tests/README.md index 8c67f62..a15b705 100644 --- a/tests/README.md +++ b/tests/README.md @@ -121,3 +121,11 @@ Playwright Page。Vite 固定运行于 `127.0.0.1:5180`;分别传入 `http` 仅在浏览器内替换静态资源进行部署前验证,不修改站点。 - 前端单元/集成 72 项通过;新增列宽计算工具覆盖率 100%。Node 原生覆盖率 不涵盖 Vite SSR 动态载入的 Vue 和指令模块,真实 DOM 行为由浏览器验收覆盖。 + +### 仪表盘刷新按钮 + +- `tests/browser/dashboard-refresh.cjs` 验证深浅主题和 1440/640/390px 屏宽下的左右留白、 + 图标间距、移动端图标及加载动画居中,同时确认禁用加载状态和两类数据刷新请求。 +- 使用 `FCB_TEST_PASSWORD`、可选 `FCB_TEST_URL` 和 `FCB_FRONTEND_DIST`,运行方式同表格验收脚本。 +- 72 项前端单元/集成与覆盖率检查、类型检查、架构检查和生产构建通过; + 本轮仅修改仪表盘按钮样式,未变更后端。Vue 样式行为通过真实浏览器测量验证。 diff --git a/tests/browser/dashboard-refresh.cjs b/tests/browser/dashboard-refresh.cjs new file mode 100644 index 0000000..5845769 --- /dev/null +++ b/tests/browser/dashboard-refresh.cjs @@ -0,0 +1,24 @@ +const {chromium}=require('playwright');const {expect}=require('playwright/test');const assert=require('node:assert/strict');const fs=require('node:fs');const path=require('node:path'); +const site=process.env.FCB_TEST_URL||'https://filetest.orionc.me'; +(async()=>{const browser=await chromium.launch({headless:false});try{ + const context=await browser.newContext({viewport:{width:1440,height:1000},colorScheme:'dark'});const page=await context.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message)); + const login=await page.request.post(site+'/admin/login',{data:{password:process.env.FCB_TEST_PASSWORD}});const token=(await login.json()).detail.token;assert.ok(token); + await context.addInitScript(token=>localStorage.setItem('token',token),token); + if(process.env.FCB_FRONTEND_DIST)await page.route(site+'/**',async route=>{const u=new URL(route.request().url());const rel=u.pathname==='/'?'index.html':u.pathname.startsWith('/theme-assets/')?u.pathname.slice(14):null;const file=rel&&path.join(process.env.FCB_FRONTEND_DIST,rel);if(file&&fs.existsSync(file)&&fs.statSync(file).isFile())await route.fulfill({path:file});else await route.continue()}); + await page.goto(site+'/#/admin/dashboard');const button=page.getByRole('button',{name:'刷新数据',exact:true});await expect(button).toBeEnabled(); + let hold=false;const gates=[];const counts={dashboard:0,analytics:0}; + for(const endpoint of Object.keys(counts))await page.route(site+'/admin/'+endpoint+'**',async route=>{counts[endpoint]++;if(hold)await new Promise(r=>gates.push(r));await route.continue()}); + const geometry=()=>button.evaluate(b=>{const icon=b.querySelector('svg,.animate-spin'),label=b.querySelector('span'),r=b.getBoundingClientRect(),i=icon.getBoundingClientRect(),l=label.getBoundingClientRect(),s=getComputedStyle(b);return {width:r.width,height:r.height,left:i.left-r.left,right:r.right-l.right,gap:l.left-i.right,centerDelta:(i.left+i.right-r.left-r.right)/2,paddingLeft:parseFloat(s.paddingLeft),paddingRight:parseFloat(s.paddingRight)}}); + for(const theme of ['dark','light']){ + await page.emulateMedia({colorScheme:theme}); + for(const width of [1440,640,390]){ + await page.setViewportSize({width,height:1000});await button.scrollIntoViewIfNeeded();const idle=await geometry(); + if(width>=640){assert.ok(idle.paddingLeft>=15&&idle.paddingRight>=15,JSON.stringify(idle));assert.ok(idle.gap>=7,JSON.stringify(idle));assert.ok(idle.left>=15&&idle.right>=15,JSON.stringify(idle))}else assert.ok(Math.abs(idle.centerDelta)<1,JSON.stringify(idle)); + hold=true;await button.click();await expect(button).toBeDisabled();await expect.poll(()=>gates.length).toBe(2); + const loading=await geometry();if(width>=640)assert.ok(loading.gap>=7,JSON.stringify(loading));else assert.ok(Math.abs(loading.centerDelta)<1,JSON.stringify(loading)); + hold=false;gates.splice(0).forEach(r=>r());await expect(button).toBeEnabled(); + await page.screenshot({path:`/tmp/fcb-refresh-${theme}-${width}.png`}); + } + } + assert.deepEqual(counts,{dashboard:6,analytics:6});assert.deepEqual(errors,[]);console.log('PASS: dark/light at 1440/640/390; desktop padding/gap, mobile icon/spinner centering; both refresh requests and disabled loading state.'); +}finally{await browser.close()}})().catch(e=>{console.error(e);process.exitCode=1}); From 3d70f67cf7edcc40d6fc107807bdb0083da5ef9f Mon Sep 17 00:00:00 2001 From: Orion Date: Sat, 19 Sep 2026 01:24:16 +0800 Subject: [PATCH 10/10] =?UTF-8?q?=E2=9C=A8=20feat:=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E5=8D=95=E4=B8=AA=E3=80=81=E9=80=89=E4=B8=AD=E5=8F=8A=E5=85=A8?= =?UTF-8?q?=E9=87=8F=E6=89=8B=E5=8A=A8=E6=A3=80=E6=B5=8B=E4=B8=8B=E8=BD=BD?= =?UTF-8?q?=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 默认关闭定时检测,取消页面加载、翻页和刷新列表触发检测 * 提供明确的检测可下载状态入口,支持全量跨分页和选中文件 * 逐个读取文件并显示进度,支持取消及过期响应隔离 * 保持检测结果标签与时间展示,验证桌面和移动端交互 * 补充手动范围、失败重试、取消及跨页全量检测的集成验收 --- src/composables/useDownloadChecks.ts | 90 ++++++++++----- src/services/download-check.ts | 3 + src/views/manage/FileManageView.vue | 23 +++- tests/README.md | 14 +++ tests/browser/admin-tables.cjs | 1 + tests/browser/manual-download-checks.cjs | 64 +++++++++++ tests/downloadChecks.integration.test.mjs | 134 +++++++++++++--------- 7 files changed, 243 insertions(+), 86 deletions(-) create mode 100644 tests/browser/manual-download-checks.cjs diff --git a/src/composables/useDownloadChecks.ts b/src/composables/useDownloadChecks.ts index 8130faf..2be2474 100644 --- a/src/composables/useDownloadChecks.ts +++ b/src/composables/useDownloadChecks.ts @@ -1,13 +1,15 @@ -import { onScopeDispose, ref, watch, type Ref } from 'vue' +import { onScopeDispose, ref, type Ref } from 'vue' import { DownloadCheckService, ConfigService } from '@/services' import type { DownloadCheck } from '@/types/download-check' export function useDownloadChecks(files: Ref<{ id: number }[]>) { const checks = ref>({}) - const interval = ref(300) + const interval = ref(0) const saving = ref(false) const error = ref('') const checking = ref(false) + const progress = ref({ completed: 0, total: 0 }) + const progressText = ref('') let controller: AbortController | undefined let timer: ReturnType | undefined let disposed = false @@ -22,50 +24,82 @@ export function useDownloadChecks(files: Ref<{ id: number }[]>) { else void refresh() }, interval.value * 1000) } - const refresh = async () => { + const cancel = () => { controller?.abort() + controller = undefined + for (const [id, result] of Object.entries(checks.value)) { + if (result.status === 'checking') checks.value[Number(id)] = { + ...result, status: 'unknown', message: '检测已取消' + } + } + if (checking.value) progressText.value = '已取消' + checking.value = false + schedule() + } + const run = async (requestedIds?: number[]) => { + if (checking.value || disposed) return const current = new AbortController() controller = current clearTimeout(timer) checking.value = true - const ids = files.value.map(file => file.id) - checks.value = Object.fromEntries(ids.map(id => [id, { - ...statusFor(id), status: 'checking', message: '正在检测' - }])) + error.value = '' + progress.value = { completed: 0, total: 0 } + progressText.value = requestedIds ? '检测中' : '正在读取全部文件' + const isCurrent = () => controller === current && !current.signal.aborted && !disposed try { - for (let offset = 0; offset < ids.length; offset += 20) { - const batch = ids.slice(offset, offset + 20) + let ids = requestedIds + if (!ids) { + const response = await DownloadCheckService.listIds(current.signal) + if (!isCurrent()) return + if (response.code !== 200 || !Array.isArray(response.detail)) throw new Error('无法读取全部文件') + ids = response.detail + } + ids = [...new Set(ids)] + progress.value.total = ids.length + progressText.value = '检测中' + // A single file per request limits each run to one active storage read. + for (const id of ids) { + if (!isCurrent()) return + checks.value[id] = { ...statusFor(id), status: 'checking', message: '正在检测' } try { - const response = await DownloadCheckService.check(batch, current.signal) - if (current.signal.aborted || disposed) return + const response = await DownloadCheckService.check([id], current.signal) + if (!isCurrent()) return if (response.code !== 200 || !Array.isArray(response.detail)) throw new Error('检测请求失败') - for (const id of batch) { - checks.value[id] = response.detail.find(item => item.id === id) ?? { - id, status: 'unknown', message: '未返回检测结果,请重试', checkedAt: null - } + checks.value[id] = response.detail.find(item => item.id === id) ?? { + id, status: 'unknown', message: '未返回检测结果,请重试', checkedAt: null } } catch { - if (current.signal.aborted || disposed) return - for (const id of batch) checks.value[id] = { - id, status: 'unknown', message: '检测请求失败,请刷新重试', checkedAt: null - } + if (!isCurrent()) return + checks.value[id] = { id, status: 'unknown', message: '检测请求失败,请重试', checkedAt: null } } + progress.value.completed++ + } + progressText.value = ids.length ? '检测完成' : '没有可检测的文件' + } catch { + if (isCurrent()) { + error.value = '无法读取全部文件,请重试' + progressText.value = '检测未开始' } } finally { - if (controller === current && !disposed) { + if (isCurrent()) { + controller = undefined checking.value = false schedule() } } } + const refresh = () => run(files.value.map(file => file.id)) + const checkIds = (ids: number[]) => run(ids) + const checkAll = () => run() const loadInterval = async () => { try { const response = await ConfigService.getConfig() - if (!disposed && response.code === 200) { - interval.value = response.detail?.downloadCheckInterval ?? 300 - schedule() + if (response.code !== 200) throw new Error('config failed') + if (!disposed) { + interval.value = response.detail?.downloadCheckInterval ?? 0 + if (!checking.value) schedule() } - } catch { error.value = '无法读取检测间隔,暂按 5 分钟刷新' } + } catch { error.value = '无法读取检测间隔,请手动检测' } } const saveInterval = async (value: number) => { if (saving.value) return @@ -75,16 +109,16 @@ export function useDownloadChecks(files: Ref<{ id: number }[]>) { const response = await ConfigService.updateConfig({ downloadCheckInterval: value }) if (response.code !== 200) throw new Error('save failed') interval.value = value - schedule() + if (!checking.value) schedule() } catch { error.value = '检测间隔保存失败,请重试' } finally { saving.value = false } } - // Every successful list load (refresh, page, filter, or edit) gets fresh results. - watch(files, () => { void refresh() }) + // Loading, refreshing, filtering and paginating the list never initiate checks. onScopeDispose(() => { disposed = true controller?.abort() clearTimeout(timer) }) - return { checks, interval, saving, error, checking, statusFor, refresh, loadInterval, saveInterval } + return { checks, interval, saving, error, checking, progress, progressText, statusFor, + refresh, checkIds, checkAll, cancel, loadInterval, saveInterval } } diff --git a/src/services/download-check.ts b/src/services/download-check.ts index c4ed481..f1b282c 100644 --- a/src/services/download-check.ts +++ b/src/services/download-check.ts @@ -3,6 +3,9 @@ import type { ApiResponse } from '@/types' import type { DownloadCheck } from '@/types/download-check' export const DownloadCheckService = { + listIds(signal?: AbortSignal): Promise> { + return api.get('/admin/file/download-check-ids', { signal }) + }, check(ids: number[], signal?: AbortSignal): Promise> { return api.post('/admin/file/download-check', { ids }, { signal, timeout: 70000 }) } diff --git a/src/views/manage/FileManageView.vue b/src/views/manage/FileManageView.vue index 5d24ef3..d09f377 100644 --- a/src/views/manage/FileManageView.vue +++ b/src/views/manage/FileManageView.vue @@ -16,9 +16,9 @@
- 仅检测当前页;刷新列表会重新检测,不消耗取件次数。 + 检测选中可下载状态({{ selectedCount }}) + 检测可下载状态 + 取消检测 + {{ downloadProgressText }} {{ downloadProgress.completed }}/{{ downloadProgress.total }} {{ checkIntervalError }}
@@ -380,7 +383,10 @@ {{ file.displayHealthState }} - +
+ + 检测可下载状态 +
{{ file.code }} · {{ file.displaySize }} {{ file.displayUsage }} @@ -714,7 +720,10 @@
- +
+ + 检测可下载状态 +
@@ -1880,7 +1889,9 @@ const { const { interval: downloadCheckInterval, saving: savingCheckInterval, error: checkIntervalError, - statusFor: downloadStatusFor, loadInterval: loadCheckInterval, saveInterval: saveCheckInterval + statusFor: downloadStatusFor, loadInterval: loadCheckInterval, saveInterval: saveCheckInterval, + checking: checkingDownloads, progress: downloadProgress, progressText: downloadProgressText, + checkIds: checkDownloadIds, checkAll: checkAllDownloads, cancel: cancelDownloadChecks } = useDownloadChecks(tableData) const handleCheckIntervalChange = (event: Event) => { void saveCheckInterval(Number((event.target as HTMLSelectElement).value)) diff --git a/tests/README.md b/tests/README.md index a15b705..aea3c4b 100644 --- a/tests/README.md +++ b/tests/README.md @@ -129,3 +129,17 @@ Playwright Page。Vite 固定运行于 `127.0.0.1:5180`;分别传入 `http` - 使用 `FCB_TEST_PASSWORD`、可选 `FCB_TEST_URL` 和 `FCB_FRONTEND_DIST`,运行方式同表格验收脚本。 - 72 项前端单元/集成与覆盖率检查、类型检查、架构检查和生产构建通过; 本轮仅修改仪表盘按钮样式,未变更后端。Vue 样式行为通过真实浏览器测量验证。 + +### 手动检测范围与取消 + +- 默认关闭定时检测;进入页面、列表刷新、搜索、分页都不会主动读取文件。 +- 每行「检测可下载状态」检测单个文件;勾选检测只处理选中 ID;顶部同名按钮 + 检测全部未回收文件,包含当前过滤和分页之外的文件。 +- 每次只发起一个文件的检测请求,显示已处理/总数,可取消后续请求。 +- `downloadChecks.integration.test.mjs` 覆盖默认静默、选择去重、串行请求、失败重试、 + 全量 ID 枚举、空结果、取消、旧响应隔离和卸载清理。 +- `tests/browser/manual-download-checks.cjs` 通过 25 文件的受控 API 响应验证跨页全量、 + 单个、选中、取消、移动布局,防止测试向真实网盘批量发起请求。 + 可使用 `FCB_TEST_TOKEN` 或 `FCB_TEST_PASSWORD`;可选本地前端产物路径。 +- 当前前端单元/集成 75 项通过,架构/类型/构建通过;Node 覆盖率不覆盖 SSR 动态 Vue 模块, + 交互另经真实浏览器验证。此前自动随列表刷新的行为已撤销。 diff --git a/tests/browser/admin-tables.cjs b/tests/browser/admin-tables.cjs index 2a88c1f..286bbf9 100644 --- a/tests/browser/admin-tables.cjs +++ b/tests/browser/admin-tables.cjs @@ -23,6 +23,7 @@ const site=process.env.FCB_TEST_URL || 'https://filetest.orionc.me'; await page.goto(site+'/#/admin/files'); const all=page.locator('.data-table-2026 table'); await all.getByRole('status').first().waitFor(); + await page.getByTitle('检测全部文件,包括未显示的分页', {exact:true}).click(); await all.getByRole('status').filter({hasText:'可下载'}).first().waitFor(); const statuses=await all.getByRole('status').evaluateAll(nodes=>nodes.map(n=>({children:n.children.length,title:n.getAttribute('title'),text:n.textContent}))); statuses.forEach(s=>{assert.ok(s.children<=2,JSON.stringify(s));assert.equal(s.title,null)}); diff --git a/tests/browser/manual-download-checks.cjs b/tests/browser/manual-download-checks.cjs new file mode 100644 index 0000000..756a18a --- /dev/null +++ b/tests/browser/manual-download-checks.cjs @@ -0,0 +1,64 @@ +const { chromium } = require('playwright') +const { expect } = require('playwright/test') +const assert = require('node:assert/strict') +const fs = require('node:fs'), path = require('node:path') +const site = process.env.FCB_TEST_URL || 'https://filetest.orionc.me' +;(async () => { + const browser = await chromium.launch({ headless: false }) + try { + const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } }) + const page = await context.newPage(), errors = [] + page.on('pageerror', error => errors.push(error.message)) + let token = process.env.FCB_TEST_TOKEN + if (!token) token = (await (await page.request.post(site + '/admin/login', { data: { password: process.env.FCB_TEST_PASSWORD } })).json()).detail.token + await context.addInitScript(token => localStorage.setItem('token', token), token) + const source = await page.request.get(site + '/admin/file/list?size=10', { headers: { Authorization: `Bearer ${token}` } }) + const base = (await source.json()).detail.data[0];assert.ok(base, 'Test site needs one file for its fixture schema') + const files = Array.from({ length: 25 }, (_, index) => ({ ...base, id: 1001 + index, prefix: `manual-check-${index + 1}`, code: `TEST${1001 + index}` })) + if (process.env.FCB_FRONTEND_DIST) await page.route(site + '/**', async route => { + const u = new URL(route.request().url()), relative = u.pathname === '/' ? 'index.html' : u.pathname.startsWith('/theme-assets/') ? u.pathname.slice(14) : null + const file = relative && path.join(process.env.FCB_FRONTEND_DIST, relative) + if (file && fs.existsSync(file) && fs.statSync(file).isFile()) await route.fulfill({ path: file });else await route.continue() + }) + await page.route(site + '/admin/config/get', async route => { const response = await route.fetch(), body = await response.json();body.detail.downloadCheckInterval = 0;await route.fulfill({ json: body }) }) + await page.route(site + '/admin/file/list**', async route => { + const u = new URL(route.request().url()), page = Number(u.searchParams.get('page') || 1), size = Number(u.searchParams.get('size') || 10) + await route.fulfill({ json: { code: 200, detail: { page, size, total: 25, data: files.slice((page - 1) * size, page * size), summary: { totalFiles: 25 } } } }) + }) + let calls = [], active = 0, peak = 0, hold = false, release, enumerations = 0 + await page.route(site + '/admin/file/download-check-ids', async route => { enumerations++;await route.fulfill({ json: { code: 200, detail: files.map(f => f.id) } }) }) + await page.route(site + '/admin/file/download-check', async route => { + const ids = route.request().postDataJSON().ids;calls.push(ids);active++;peak = Math.max(peak, active) + try { + if (hold) await new Promise(resolve => { release = resolve }) + await route.fulfill({ json: { code: 200, detail: ids.map(id => ({ id, status: 'available', message: 'probe', checkedAt: new Date().toISOString() })) } }) + } catch (error) { if (!String(error).includes('closed') && !String(error).includes('Invalid Interception')) throw error } + finally { active-- } + }) + await page.goto(site + '/#/admin/files') + const table = page.locator('.data-table-2026'), rows = table.locator('tbody tr') + await expect(rows).toHaveCount(10) + await expect(page.getByLabel('自动检测当前页')).toHaveValue('0') + assert.equal(calls.length, 0) + await table.getByRole('button', { name: '刷新列表', exact: true }).click();await expect(rows).toHaveCount(10) + await table.getByRole('button', { name: '下一页', exact: true }).click();await expect(rows.first()).toContainText('TEST1011') + await page.clock.install();await page.clock.fastForward(3600000);await page.clock.resume();assert.equal(calls.length, 0) + await rows.first().getByRole('button', { name: '检测可下载状态', exact: true }).click() + await expect(page.getByRole('status').filter({ hasText: '检测完成 1/1' })).toBeVisible();assert.deepEqual(calls, [[1011]]) + calls = [];await rows.nth(0).getByRole('checkbox').check();await rows.nth(1).getByRole('checkbox').check() + await page.getByRole('button', { name: '检测选中可下载状态(2)', exact: true }).click() + await expect(page.getByRole('status').filter({ hasText: '检测完成 2/2' })).toBeVisible();assert.deepEqual(calls, [[1011], [1012]]) + calls = [];await page.getByTitle('检测全部文件,包括未显示的分页', { exact: true }).click() + await expect(page.getByRole('status').filter({ hasText: '检测完成 25/25' })).toBeVisible() + assert.equal(enumerations, 1);assert.deepEqual(calls, files.map(f => [f.id]));assert.equal(peak, 1) + calls = [];hold = true;await page.getByTitle('检测全部文件,包括未显示的分页', { exact: true }).click() + await expect.poll(() => calls.length).toBe(1);await page.getByRole('button', { name: '取消检测', exact: true }).click() + await expect(page.getByRole('status').filter({ hasText: '已取消' })).toBeVisible();hold = false;release() + await expect.poll(() => active).toBe(0);assert.equal(calls.length, 1) + await page.setViewportSize({ width: 390, height: 844 });await expect(page.getByTitle('检测全部文件,包括未显示的分页')).toBeVisible() + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)) + await page.screenshot({ path: '/tmp/fcb-manual-check-mobile.png' }) + await page.setViewportSize({ width: 1440, height: 1000 });await page.screenshot({ path: '/tmp/fcb-manual-check-desktop.png' }) + assert.deepEqual(errors, []);console.log('PASS: no checks on entry/refresh/pagination/time; single, selected, all 25 across pages, serial requests, cancel, mobile layout.') + } finally { await browser.close() } +})().catch(error => { console.error(error);process.exitCode = 1 }) diff --git a/tests/downloadChecks.integration.test.mjs b/tests/downloadChecks.integration.test.mjs index 07030a3..40a2c86 100644 --- a/tests/downloadChecks.integration.test.mjs +++ b/tests/downloadChecks.integration.test.mjs @@ -11,60 +11,90 @@ before(async () => { }) after(async () => await server?.close()) const ok = ids => ({ code: 200, detail: ids.map(id => ({id, status: 'available', message: 'ok', checkedAt: '2026-09-18T00:00:00Z'})) }) -test('refresh batches large pages, preserves list on failure, and retries', async () => { - const scope = effectScope(), files = ref(Array.from({length: 45}, (_, i) => ({id: i + 1}))) - const flow = scope.run(() => create(files)), original = service.check, batches = [] - try { - service.check = async ids => { batches.push(ids.length); if (ids[0] === 21) throw Error('offline'); return ok(ids) } - await flow.refresh() - assert.deepEqual(batches, [20,20,5]); assert.equal(files.value.length, 45) - assert.equal(flow.statusFor(1).status, 'available'); assert.equal(flow.statusFor(21).status, 'unknown') - service.check = async ids => ok(ids); await flow.refresh() - assert.equal(flow.statusFor(21).status, 'available') - } finally { scope.stop(); service.check = original } + +test('manual mode does not check on mount, config load, refresh, pagination or elapsed time', async t => { + const scope=effectScope(),files=ref([{id:1}]),f=scope.run(()=>create(files)) + const oldCheck=service.check,oldGet=config.getConfig;let calls=0 + t.mock.timers.enable({apis:['setTimeout']}) + try { + service.check=async ids=>{calls++;return ok(ids)} + config.getConfig=async()=>({code:200,detail:{downloadCheckInterval:0}}) + assert.equal(f.interval.value,0);await f.loadInterval() + files.value=[{id:2}];await nextTick();files.value=[{id:2}];await nextTick() + t.mock.timers.tick(3600000);assert.equal(calls,0) + await f.checkIds([2]);assert.equal(calls,1) + } finally {scope.stop();service.check=oldCheck;config.getConfig=oldGet;t.mock.timers.reset()} }) -test('navigation cancels old checks and stale responses cannot change current page', async () => { - const scope = effectScope(), files = ref([{id: 1}]), flow = scope.run(() => create(files)) - const original = service.check, pending = new Map(), signals = [] - service.check = (ids, signal) => { signals.push(signal); return new Promise(resolve => pending.set(ids[0], resolve)) } - try { - const first = flow.refresh(); files.value = [{id: 2}]; await nextTick() - assert.equal(signals[0].aborted, true) - pending.get(2)(ok([2])); await new Promise(resolve => setImmediate(resolve)) - pending.get(1)(ok([1])); await first - assert.deepEqual(Object.keys(flow.checks.value), ['2']) - assert.equal(flow.statusFor(2).status, 'available') - } finally { scope.stop(); service.check = original } +test('single and selected checks deduplicate IDs, run sequentially, tolerate failure and report progress',async()=>{ + const scope=effectScope(),files=ref([{id:1},{id:2},{id:3}]),f=scope.run(()=>create(files)) + const original=service.check;let active=0,max=0;const seen=[] + try { + service.check=async ids=>{active++;max=Math.max(max,active);seen.push(ids);await Promise.resolve();active--;if(ids[0]===2)throw Error('offline');return ok(ids)} + await f.checkIds([1,2,1,3]);assert.deepEqual(seen,[[1],[2],[3]]);assert.equal(max,1) + assert.equal(f.statusFor(1).status,'available');assert.equal(f.statusFor(2).status,'unknown') + assert.deepEqual(f.progress.value,{completed:3,total:3});assert.equal(files.value.length,3) + service.check=async ids=>ok(ids);await f.checkIds([2]);assert.equal(f.statusFor(2).status,'available') + }finally{scope.stop();service.check=original} }) -test('interval settings persist, save failures retain old value, manual refresh works with timer off', async () => { - const scope = effectScope(), flow = scope.run(() => create(ref([{id: 1}]))) - const oldGet = config.getConfig, oldSave = config.updateConfig, oldCheck = service.check - try { - config.getConfig = async () => ({code: 200, detail: {downloadCheckInterval: 60}}) - await flow.loadInterval(); assert.equal(flow.interval.value, 60) - config.updateConfig = async data => {assert.equal(data.downloadCheckInterval, 0); return {code:200}} - await flow.saveInterval(0); assert.equal(flow.interval.value, 0) - config.updateConfig = async () => {throw Error('offline')} - await flow.saveInterval(300); assert.equal(flow.interval.value, 0); assert.ok(flow.error.value) - service.check = async ids => ok(ids); await flow.refresh(); assert.equal(flow.statusFor(1).status,'available') - } finally {scope.stop();config.getConfig=oldGet;config.updateConfig=oldSave;service.check=oldCheck} +test('all-files check includes IDs outside the visible page and ignores changing list filters',async()=>{ + const scope=effectScope(),files=ref([{id:1}]),f=scope.run(()=>create(files)) + const oldCheck=service.check,oldIds=service.listIds;const seen=[] + try { + service.listIds=async()=>({code:200,detail:[1,2,3,4]}) + service.check=async ids=>{seen.push(ids[0]);files.value=[{id:99}];await nextTick();return ok(ids)} + await f.checkAll();assert.deepEqual(seen,[1,2,3,4]);assert.equal(f.progress.value.completed,4) + assert.equal(f.statusFor(4).status,'available');assert.equal(f.statusFor(99).status,'unknown') + }finally{scope.stop();service.check=oldCheck;service.listIds=oldIds} }) -test('automatic timer refreshes and stops after scope disposal', async t => { - const scope=effectScope(), flow=scope.run(()=>create(ref([{id:1}]))), original=service.check - let calls=0 - t.mock.timers.enable({apis:['setTimeout']}) - try { - service.check=async ids=>{calls++;return ok(ids)} - await flow.refresh(); assert.equal(calls,1) - t.mock.timers.tick(300000); await new Promise(resolve=>setImmediate(resolve));assert.equal(calls,2) - scope.stop();t.mock.timers.tick(300000);assert.equal(calls,2) - } finally {scope.stop();service.check=original;t.mock.timers.reset()} +test('cancel stops subsequent requests and stale responses cannot overwrite a new run',async()=>{ + const scope=effectScope(),f=scope.run(()=>create(ref([{id:1},{id:2}]))),old=service.check + let resolveFirst,signal;const seen=[] + try { + service.check=(ids,s)=>{signal=s;seen.push(ids[0]);return new Promise(r=>resolveFirst=r)} + const first=f.checkIds([1,2]);await f.checkIds([3]);assert.deepEqual(seen,[1]) + f.cancel();assert.equal(signal.aborted,true);assert.equal(f.checking.value,false) + assert.equal(f.statusFor(1).status,'unknown');assert.equal(f.progressText.value,'已取消') + service.check=async ids=>ok(ids);await f.checkIds([1]);const fresh=f.statusFor(1) + resolveFirst({code:200,detail:[{id:1,status:'unavailable'}]});await first + assert.deepEqual(f.statusFor(1),fresh);assert.deepEqual(seen,[1]) + }finally{scope.stop();service.check=old} }) -test('status component renders all states and the last checked time', async () => { - const {createSSRApp}=await import('vue'), {renderToString}=await import('vue/server-renderer') - const Component=(await server.ssrLoadModule('/src/components/manage/DownloadCheckStatus.vue')).default - for (const [status,label] of Object.entries({available:'可下载',unavailable:'不可下载',unknown:'未检测',checking:'检测中'})) { - const html=await renderToString(createSSRApp(Component,{result:{id:1,status,message:'reason',checkedAt:'2026-09-18T00:00:00Z'},dark:false})) - assert.ok(html.includes(label));assert.ok(!html.includes('reason'));assert.ok(html.includes('2026')) - } +test('all-files enumeration handles failure, cancellation, empty results and disposal',async()=>{ + const oldIds=service.listIds,oldCheck=service.check,scope=effectScope(),f=scope.run(()=>create(ref([]))) + let calls=0 + try { + service.check=async ids=>{calls++;return ok(ids)} + service.listIds=async()=>{throw Error('offline')};await f.checkAll();assert.ok(f.error.value);assert.equal(calls,0) + service.listIds=async()=>({code:200,detail:[]});await f.checkAll();assert.equal(f.progressText.value,'没有可检测的文件') + let resolveIds,signal;service.listIds=s=>{signal=s;return new Promise(r=>resolveIds=r)} + const pending=f.checkAll();scope.stop();assert.equal(signal.aborted,true);resolveIds({code:200,detail:[1]});await pending;assert.equal(calls,0) + }finally{scope.stop();service.listIds=oldIds;service.check=oldCheck} +}) +test('interval settings persist, save failures retain old value, manual works with timer off',async()=>{ + const scope=effectScope(),f=scope.run(()=>create(ref([{id:1}]))),oldGet=config.getConfig,oldSave=config.updateConfig,oldCheck=service.check + try { + config.getConfig=async()=>({code:200,detail:{downloadCheckInterval:60}});await f.loadInterval();assert.equal(f.interval.value,60) + config.updateConfig=async data=>{assert.equal(data.downloadCheckInterval,0);return {code:200}} + await f.saveInterval(0);assert.equal(f.interval.value,0) + config.updateConfig=async()=>{throw Error('offline')};await f.saveInterval(300);assert.equal(f.interval.value,0);assert.ok(f.error.value) + service.check=async ids=>ok(ids);await f.refresh();assert.equal(f.statusFor(1).status,'available') + }finally{scope.stop();config.getConfig=oldGet;config.updateConfig=oldSave;service.check=oldCheck} +}) +test('explicitly enabled timer runs only after its interval and stops on disposal',async t=>{ + const scope=effectScope(),files=ref([{id:1}]),f=scope.run(()=>create(files)),oldCheck=service.check,oldGet=config.getConfig + let calls=0;t.mock.timers.enable({apis:['setTimeout']}) + try { + service.check=async ids=>{calls++;return ok(ids)};config.getConfig=async()=>({code:200,detail:{downloadCheckInterval:300}}) + await f.loadInterval();files.value=[{id:2}];await nextTick();assert.equal(calls,0) + t.mock.timers.tick(300000);await new Promise(r=>setImmediate(r));assert.equal(calls,1) + scope.stop();t.mock.timers.tick(300000);assert.equal(calls,1) + }finally{scope.stop();service.check=oldCheck;config.getConfig=oldGet;t.mock.timers.reset()} +}) +test('status component renders only label and last checked time',async()=>{ + const {createSSRApp}=await import('vue'),{renderToString}=await import('vue/server-renderer') + const Component=(await server.ssrLoadModule('/src/components/manage/DownloadCheckStatus.vue')).default + for(const [status,label] of Object.entries({available:'可下载',unavailable:'不可下载',unknown:'未检测',checking:'检测中'})){ + const html=await renderToString(createSSRApp(Component,{result:{id:1,status,message:'reason',checkedAt:'2026-09-18T00:00:00Z'},dark:false})) + assert.ok(html.includes(label));assert.ok(!html.includes('reason'));assert.ok(html.includes('2026')) + } })