✨ feat: 支持单个、选中及全量手动检测下载状态

* 默认关闭定时检测,取消页面加载、翻页和刷新列表触发检测
* 提供明确的检测可下载状态入口,支持全量跨分页和选中文件
* 逐个读取文件并显示进度,支持取消及过期响应隔离
* 保持检测结果标签与时间展示,验证桌面和移动端交互
* 补充手动范围、失败重试、取消及跨页全量检测的集成验收
This commit is contained in:
orion committed 2026-09-19 01:24:16 +08:00
1 parent fe6d812857
commit 3d70f67cf7
7 files changed
+233 -76

No files matched your search

+59 -25
View File
@@ -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<Record<number, DownloadCheck>>({})
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<typeof setTimeout> | 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
}
}
} 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 }
}
+3
View File
@@ -3,6 +3,9 @@ import type { ApiResponse } from '@/types'
import type { DownloadCheck } from '@/types/download-check'
export const DownloadCheckService = {
listIds(signal?: AbortSignal): Promise<ApiResponse<number[]>> {
return api.get('/admin/file/download-check-ids', { signal })
},
check(ids: number[], signal?: AbortSignal): Promise<ApiResponse<DownloadCheck[]>> {
return api.post('/admin/file/download-check', { ids }, { signal, timeout: 70000 })
}
+16 -5
View File
@@ -16,9 +16,9 @@
<div class="mb-4 flex flex-wrap items-center gap-3 text-sm" :class="mutedTextClass">
<label class="flex items-center gap-2">
下载状态刷新
自动检测当前页
<select :value="downloadCheckInterval" :disabled="savingCheckInterval" class="min-h-11 rounded-lg border px-3" :class="fieldClass" @change="handleCheckIntervalChange">
<option :value="0">仅手动刷新</option>
<option :value="0">仅手动检测</option>
<option :value="30">每 30 秒</option>
<option :value="60">每分钟</option>
<option :value="300">每 5 分钟</option>
@@ -26,7 +26,10 @@
<option :value="1800">每 30 分钟</option>
</select>
</label>
<span class="text-xs">仅检测当前页;刷新列表会重新检测,不消耗取件次数。</span>
<BaseButton variant="secondary" :disabled="!hasSelectedFiles || checkingDownloads" @click="checkDownloadIds([...selectedFileIds])">检测选中可下载状态({{ selectedCount }})</BaseButton>
<BaseButton variant="secondary" :disabled="checkingDownloads" @click="checkAllDownloads" title="检测全部文件,包括未显示的分页">检测可下载状态</BaseButton>
<BaseButton v-if="checkingDownloads" variant="outline" @click="cancelDownloadChecks">取消检测</BaseButton>
<span v-if="downloadProgressText" role="status">{{ downloadProgressText }} {{ downloadProgress.completed }}/{{ downloadProgress.total }}</span>
<span v-if="checkIntervalError" role="alert" class="text-red-500">{{ checkIntervalError }}</span>
</div>
@@ -380,7 +383,10 @@
{{ file.displayHealthState }}
</span>
</div>
<DownloadCheckStatus class="mt-2" :result="downloadStatusFor(file.id)" :dark="isDarkMode" />
<div class="mt-2 flex items-center justify-between gap-2">
<DownloadCheckStatus :result="downloadStatusFor(file.id)" :dark="isDarkMode" />
<BaseButton variant="outline" size="sm" :disabled="checkingDownloads" @click="checkDownloadIds([file.id])">检测可下载状态</BaseButton>
</div>
<div class="mt-2 grid grid-cols-2 gap-x-3 gap-y-1 text-xs" :class="[mutedTextClass]">
<span>{{ file.code }} · {{ file.displaySize }}</span>
<span class="text-right">{{ file.displayUsage }}</span>
@@ -714,7 +720,10 @@
</span>
</td>
<td class="px-6 py-4" :class="primaryTextClass">
<div class="flex items-center gap-2">
<DownloadCheckStatus :result="downloadStatusFor(file.id)" :dark="isDarkMode" />
<BaseButton variant="outline" size="sm" :disabled="checkingDownloads" @click="checkDownloadIds([file.id])">检测可下载状态</BaseButton>
</div>
</td>
<td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<div class="flex items-center justify-end gap-2">
@@ -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))
+14
View File
@@ -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 模块,
交互另经真实浏览器验证。此前自动随列表刷新的行为已撤销。
+1
View File
@@ -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)});
+64
View File
@@ -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 })
+76 -46
View File
@@ -11,56 +11,86 @@ 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('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('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('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
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)}
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()}
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('status component renders all states and the last checked time', async () => {
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('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('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('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:'检测中'})){