Peach: Local-first video metadata scraper and media manager.
fix(tasks): 右侧图标控制保留优先取消与真实回执
longmeidao2eb577c862bd
diff --git a/frontend/e2e/tooltip-fidelity.test.ts b/frontend/e2e/tooltip-fidelity.test.tsindex 83ef30045..1fe58c7ba 100644--- a/frontend/e2e/tooltip-fidelity.test.ts+++ b/frontend/e2e/tooltip-fidelity.test.ts@@ -83,5 +83,37 @@ describe('共享提示的文字与锚点', () => {assert(Math.abs(geometry.tip.y + geometry.tip.h + 8 - geometry.icon.y) <= 1, JSON.stringify(geometry));} finally { await opened.close() }});+ it(`${viewport.name} 任务图标的可见提示保留独立编辑键,关闭后不串给其他控件`, async () => {+ const opened = await openItemPage(browser, '/', viewport, { ready: '[data-catalog-frame]' });+ try {+ await opened.page.evaluate(() => {+ const probe = document.createElement('div');+ probe.style.cssText = 'position:fixed;left:30px;top:200px;z-index:9999;display:flex;gap:20px';+ probe.innerHTML = '<div data-copy-bar hidden></div><button id="tip-task-control" aria-label="暂停后续任务" title="暂停后续任务" data-tooltip-copy-key="tasks.control.action.followups.pause" style="width:32px;height:32px"><svg width="16" height="16"><path d="M4 2v12M12 2v12"/></svg></button><button id="tip-other-control" aria-label="其他操作" title="其他操作" style="width:32px;height:32px">…</button>';+ document.body.append(probe);+ });+ await opened.page.locator('#tip-task-control').focus();+ const tip = opened.page.locator('#board-control-tooltip');+ await tip.waitFor({ state: 'visible' });+ assert.equal(await tip.textContent(), '暂停后续任务');+ assert.equal(await tip.getAttribute('data-copy-key'), 'tasks.control.action.followups.pause');+ assert.equal(await opened.page.locator('#tip-task-control').getAttribute('data-copy-key'), null);+ assert.equal(await tip.evaluate(node => getComputedStyle(node).pointerEvents), 'auto');+ await tip.hover();+ await opened.page.waitForTimeout(300);+ assert.equal(await tip.isVisible(), true);+ await opened.page.keyboard.press('Escape');+ await tip.waitFor({ state: 'hidden' });+ assert.equal(await tip.getAttribute('data-copy-key'), null);+ await opened.page.locator('#tip-other-control').focus();+ await tip.waitFor({ state: 'visible' });+ assert.equal(await tip.textContent(), '其他操作');+ assert.equal(await tip.getAttribute('data-copy-key'), null);+ await opened.page.keyboard.press('Escape');+ await opened.page.locator('#tip-task-control').hover();+ await tip.waitFor({ state: 'visible' });+ assert.equal(await tip.getAttribute('data-copy-key'), 'tasks.control.action.followups.pause');+ } finally { await opened.close() }+ });}});diff --git a/frontend/src/board-tooltip.ts b/frontend/src/board-tooltip.tsindex 6e92ffd4e..35733fc2d 100644--- a/frontend/src/board-tooltip.ts+++ b/frontend/src/board-tooltip.ts@@ -56,6 +56,8 @@ export function initBoardTooltip() {tip.popover = 'manual'; tip.hidden = true; document.body.append(tip);let target: HTMLElement | null = null, title = '', described: string | null = null;let timer: ReturnType<typeof setTimeout> | undefined;+ let exitTimer: ReturnType<typeof setTimeout> | undefined;+ const editableTip = () => tip.hasAttribute('data-copy-key') && Boolean(document.querySelector('[data-copy-bar]'));const place = (next: HTMLElement) => {const rect = anchorRect(next), box = tip.getBoundingClientRect();if (!rect) return;@@ -63,7 +65,9 @@ export function initBoardTooltip() {tip.style.top = `${rect.top >= box.height + 16 ? rect.top - box.height - 8 : Math.min(innerHeight - box.height - 8, rect.bottom + 8)}px`;};const hide = () => {- clearTimeout(timer); if (tip.matches(':popover-open')) tip.hidePopover(); tip.hidden = true;+ clearTimeout(timer); clearTimeout(exitTimer);+ if (tip.matches(':popover-open')) tip.hidePopover(); tip.hidden = true;+ tip.removeAttribute('data-copy-key');if (target) {if (!target.hasAttribute('title')) target.title = title;if (described === null) target.removeAttribute('aria-describedby');@@ -82,14 +86,34 @@ export function initBoardTooltip() {timer = setTimeout(() => {if (target !== next || !next.isConnected || !anchorRect(next)) return;(next.closest('dialog[open]') ?? document.body).append(tip);- tip.textContent = title; tip.hidden = false; tip.showPopover(); place(next);+ tip.textContent = title;+ const copyKey = next.getAttribute('data-tooltip-copy-key');+ if (copyKey) tip.setAttribute('data-copy-key', copyKey);+ else tip.removeAttribute('data-copy-key');+ tip.style.pointerEvents = editableTip() ? 'auto' : '';+ tip.hidden = false; tip.showPopover(); place(next);next.setAttribute('aria-describedby', [described, tip.id].filter(Boolean).join(' '));}, delay);};- document.addEventListener('pointerover', event => show(event.target, 400));- document.addEventListener('pointerout', event => { if (target && !target.contains(event.relatedTarget as Node | null)) hide() });+ document.addEventListener('pointerover', event => {+ if (editableTip()) {+ if (target?.contains(event.target as Node)) clearTimeout(exitTimer);+ if (tip.contains(event.target as Node)) { clearTimeout(exitTimer); return; }+ }+ show(event.target, 400);+ });+ document.addEventListener('pointerout', event => {+ if (!target || target.contains(event.relatedTarget as Node | null)) return;+ if (editableTip()) {+ if (tip.contains(event.relatedTarget as Node | null) || tip.hasAttribute('data-copy-inline')) return;+ clearTimeout(exitTimer); exitTimer = setTimeout(hide, 250);+ } else hide();+ });document.addEventListener('focusin', event => show(event.target, 0));- document.addEventListener('focusout', hide);+ document.addEventListener('focusout', event => {+ if (editableTip() && (tip.contains(event.relatedTarget as Node | null) || tip.hasAttribute('data-copy-inline'))) return;+ hide();+ });document.addEventListener('keydown', event => { if (event.key === 'Escape') hide() });document.addEventListener('scroll', event => {if (!target || !scrollMovesAnchor(event, target)) return;diff --git a/frontend/src/react/activity/activity-page.tsx b/frontend/src/react/activity/activity-page.tsxindex 2805b4b28..b4fd266ad 100644--- a/frontend/src/react/activity/activity-page.tsx+++ b/frontend/src/react/activity/activity-page.tsx@@ -34,7 +34,7 @@ import { Disclosure } from '../settings/section';import { BackgroundIssues } from './background-issues';import { DownloadsPanel } from './downloads-panel';import { ErrorDetails, ErrorExcerpt } from './error-excerpt';-import { TaskControls } from './task-controls';+import { TaskControlFeedback, TaskControls } from './task-controls';import {elapsedText, fetchEarlier, fetchTasks, foldByKind, foldRoutine, followupDetail, followupTally, groupFollowups, isActive,hasResultProblems, isRoutine, latestOfKind, mergeFinished, momentText, pollInterval, problemDestination, progressText,@@ -82,16 +82,19 @@ function FollowupList({ rows }: { rows: TaskRunPayload[] }) {const detail = followupDetail(row);return (<li key={row.id} data-status={row.status} data-followup-key={row.followup_key}- className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 border-t border-separator-border px-5 py-2.5">- <span className="min-w-0 break-words text-caption-1-regular text-text-primary">- {row.task_label}- </span>- <StatusBadge run={row} />- {detail- ? <span className="min-w-0 break-words text-caption-1-regular text-text-secondary">{detail}</span>- : null}- {row.control?.actions.length- ? <div className="w-full min-w-0"><TaskControls run={row} /></div> : null}+ className="flex min-w-0 flex-col gap-1 border-t border-separator-border px-5 py-2.5">+ <div className="flex min-w-0 items-start justify-between gap-3">+ <div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">+ <span className="min-w-0 break-words text-caption-1-regular text-text-primary">+ {row.task_label}+ </span>+ <StatusBadge run={row} />+ {detail+ ? <span className="min-w-0 break-words text-caption-1-regular text-text-secondary">{detail}</span>+ : null}+ </div>+ <TaskControls run={row} />+ </div>{/* 排队中的那些还没有结果:空的「技术详情」展开只有一对花括号。 */}{Object.keys(row.result_summary || {}).length? <div className="w-full min-w-0">@@ -133,13 +136,15 @@ function RunCard(})}>{/* 卡片标题比分段标题(「正在进行」)低一档,标题、时间与摘要之间同一个行距。 */}<div className="flex flex-col gap-2 px-5 py-4">- <div className="flex flex-wrap items-center gap-2">- <strong className="min-w-0 break-words text-title-3-medium text-text-primary">{run.task_label}</strong>- {badge ?? <StatusBadge run={run} />}+ <div className="flex min-w-0 items-start justify-between gap-3">+ <div className="flex min-w-0 flex-wrap items-center gap-2">+ <strong className="min-w-0 break-words text-title-3-medium text-text-primary">{run.task_label}</strong>+ {badge ?? <StatusBadge run={run} />}+ </div>+ <TaskControls run={run} /></div><p className="text-caption-1-regular text-text-secondary">{meta}</p>{children}- <TaskControls run={run} /></div>{shown ? <div className="border-t border-separator-border px-5 py-2.5"><Disclosure summary={`任务明细 · ${total.toLocaleString()} 项`}@@ -193,9 +198,9 @@ function RunningRun({ run, followups }: { run: TaskRunPayload; followups?: TaskR* 任务卡只记这一轮的历史:此刻还没解决的问题和「立即重试」在页顶「需要处理」那一块。* `latest` 说它是不是同一种任务最新的那一轮:有些任务只有那一轮还有处理入口。 */function SettledRun(- { run, followups, runs, latest, followupTotal, followupFailed = 0 }:+ { run, followups, runs, latest, followupTotal, followupFailed = 0, followupCancelled = 0 }:{ run: TaskRunPayload; followups?: TaskRunPayload[]; runs?: TaskRunPayload[]; latest: boolean;- followupTotal?: number; followupFailed?: number },+ followupTotal?: number; followupFailed?: number; followupCancelled?: number },) {/* 几批派发并成一张时,最新那一批的「已安排 64 项」说不清整件事:改说一共处理了几项、失败几项,有失败时徽章写发现问题,失败的那几条在任务明细里排在前面。 */@@ -215,7 +220,14 @@ function SettledRun(elapsed && `用时 ${elapsed}`]).filter(Boolean).join(' · ');return (<RunCard run={run} meta={meta} footer={run.error} followups={followups} followupTotal={followupTotal}- badge={batches && followupFailed ? <Chip color="yellow">发现问题</Chip> : undefined}>+ badge={followupCancelled && run.status === 'succeeded'+ ? <Chip color="neutral"><span data-copy-key={`tasks.followups.cancelled.${followupCancelled === followupTotal ? 'all' : 'partial'}`}>+ {followupCancelled === followupTotal ? '后续任务已取消' : '部分后续任务已取消'}+ </span></Chip>+ : batches && followupFailed ? <Chip color="yellow">发现问题</Chip> : undefined}>+ {followupCancelled ? <p className="text-caption-1-regular text-text-secondary">+ 后续任务已取消 {followupCancelled.toLocaleString()} 项+ </p> : null}{/* 只有一句摘要时不加项目符号:单独一个圆点读起来像漏了下文。 */}{summary.length === 1? <p className="text-caption-1-regular text-text-secondary wrap-anywhere">{summary[0]}</p>@@ -367,6 +379,7 @@ export function ActivityPage() {return (<Page>{problem ? <Note tone="error">{problem}</Note> : null}+ <TaskControlFeedback />{data.available === false? <Note tone="warning">{data.message || '数据库尚未准备好任务记录表'}</Note>: null}@@ -401,7 +414,8 @@ export function ActivityPage() {? <RunList>{folds.map(({ run, runs }) => {const tally = followupTally(counts, runs);return <SettledRun key={run.id} run={run} runs={runs} latest={newest.has(run.id)}- followups={childrenOf(runs)} followupTotal={tally.total} followupFailed={tally.failed} />;+ followups={childrenOf(runs)} followupTotal={tally.total} followupFailed={tally.failed}+ followupCancelled={tally.cancelled} />;})}</RunList>: null}{more.error ? <Note tone="error">{errorMessage(more.error)}</Note> : null}diff --git a/frontend/src/react/activity/task-controls.tsx b/frontend/src/react/activity/task-controls.tsxindex 997a2cdef..d06d910bb 100644--- a/frontend/src/react/activity/task-controls.tsx+++ b/frontend/src/react/activity/task-controls.tsx@@ -1,39 +1,98 @@/* 任务动作由服务端逐轮给出;收到控制请求不代表后台已经停稳,状态仍以轮询为准。 */-import { useQueryClient } from '@tanstack/react-query';+import { useRef } from 'react';+import { RiPauseLine, RiPlayLine, RiStopLine } from '@remixicon/react';+import { useMutation, useMutationState, useQueryClient } from '@tanstack/react-query';import { Button } from '@/components/base/buttons/button';+import { errorMessage } from '../../api';import { Note } from '../components/note';-import { busyProps, useAction } from '../settings/use-action';+import { busyProps } from '../settings/use-action';import { controlTask, isActive, TASKS_KEY, type TaskControlAction, type TaskRunPayload } from './tasks';+const CONTROL_KEY = ['task-control'] as const;+const ICONS = { pause: RiPauseLine, resume: RiPlayLine, cancel: RiStopLine };+const LABELS = { pause: '暂停', resume: '继续', cancel: '取消' };+const FOLLOWUP_LABELS = { pause: '暂停后续任务', resume: '继续后续任务', cancel: '取消后续任务' };++interface ControlCommand { id: number; label: string; action: TaskControlAction; followups: boolean }++/** 请求结果属于任务中心,任务转入终态、卸载原卡片后仍保留未接受的操作及原因。 */+export function TaskControlFeedback() {+ const mutations = useMutationState({+ filters: { mutationKey: CONTROL_KEY },+ select: (mutation) => ({+ id: mutation.mutationId,+ command: mutation.state.variables as ControlCommand | undefined,+ status: mutation.state.status,+ error: mutation.state.error,+ }),+ });+ const latest = new Map<number, { id: number; command: ControlCommand; status: string; error: unknown }>();+ for (const mutation of mutations) {+ const command = mutation.command;+ if (!command) continue;+ const previous = latest.get(command.id);+ if (!previous || previous.id < mutation.id) latest.set(command.id, { ...mutation, command });+ }+ const failed = [...latest.values()].filter((mutation) => mutation.status === 'error');+ if (!failed.length) return null;+ return <div data-task-control-feedback="" className="flex min-w-0 flex-col gap-2">+ {failed.map(({ command, error }) => <Note key={command.id} tone="error"+ title={`${command.label}:${(command.followups ? FOLLOWUP_LABELS : LABELS)[command.action]}未完成`}>+ {errorMessage(error)}+ </Note>)}+ </div>;+}+export function TaskControls({ run }: { run: TaskRunPayload }) {const client = useQueryClient();- const request = useAction();+ const pending = useRef({ change: false, cancel: false });+ const refresh = () => { void client.invalidateQueries({ queryKey: TASKS_KEY }) };+ const send = (command: ControlCommand) => controlTask(command.id, command.action);+ const change = useMutation({+ mutationKey: [...CONTROL_KEY, run.id, 'change'],+ mutationFn: send,+ onSettled: () => { pending.current.change = false; refresh() },+ });+ const cancellation = useMutation({+ mutationKey: [...CONTROL_KEY, run.id, 'cancel'],+ mutationFn: send,+ onSettled: () => { pending.current.cancel = false; refresh() },+ });const actions = run.control?.actions || [];const followups = !isActive(run);+ const cancelling = cancellation.isPending || cancellation.isSuccess;if (!actions.length) return null;const submit = (action: TaskControlAction) => {- void request.run(action, (signal) => controlTask(run.id, action, signal), () => {- void client.invalidateQueries({ queryKey: TASKS_KEY });- });+ const command = { id: run.id, label: run.task_label, action, followups };+ if (action === 'cancel') {+ if (pending.current.cancel || cancellation.isSuccess) return;+ pending.current.cancel = true;+ cancellation.mutate(command);+ } else {+ if (pending.current.change || pending.current.cancel || cancelling) return;+ pending.current.change = true;+ change.mutate(command);+ }};return (- <div className="flex min-w-0 flex-col gap-2" data-task-controls={run.id}>+ <div className="ml-auto shrink-0" data-task-controls={run.id}><div role="group" aria-label={`${run.task_label}${followups ? '后续任务' : '任务'}控制`}- className="flex flex-wrap items-center gap-2">- {actions.map((action) => <Button key={action} type="button" variant="secondary" size="small"- {...busyProps(request.busy === action)} aria-disabled={Boolean(request.busy) || undefined}- onClick={() => submit(action)}- data-copy-key={`tasks.control.action.${followups ? 'followups.' : ''}${action}`}>- {followups- ? action === 'pause' ? '暂停后续任务' : action === 'resume' ? '继续后续任务' : '取消后续任务'- : action === 'pause' ? '暂停' : action === 'resume' ? '继续' : '取消'}- </Button>)}+ className="flex items-center justify-end gap-2">+ {actions.map((action) => {+ const label = (followups ? FOLLOWUP_LABELS : LABELS)[action];+ const busy = action === 'cancel' ? cancellation.isPending : change.isPending && change.variables?.action === action;+ const unavailable = action === 'cancel' ? cancelling : change.isPending || cancelling;+ return <Button key={action} type="button" variant="secondary" size="small" iconOnly+ leadingIcon={ICONS[action]} aria-label={label} title={label}+ {...busyProps(busy)} aria-disabled={unavailable || undefined}+ onClick={() => submit(action)}+ data-tooltip-copy-key={`tasks.control.action.${followups ? 'followups.' : ''}${action}`} />;+ })}</div>- {request.error ? <Note tone="error">{request.error}</Note> : null}</div>);}diff --git a/frontend/src/react/activity/tasks.ts b/frontend/src/react/activity/tasks.tsindex e7fdce238..b9aa6fd9f 100644--- a/frontend/src/react/activity/tasks.ts+++ b/frontend/src/react/activity/tasks.ts@@ -65,15 +65,16 @@ export interface FinishedPage {/** 几轮派出的后继合在一起数:共几条、结束了几条、还有几条在排或在跑。 */export function followupTally(counts: FollowupCounts | undefined, runs: TaskRunPayload[]) {- let total = 0, active = 0, failed = 0;+ let total = 0, active = 0, failed = 0, cancelled = 0;for (const run of runs) {for (const [status, count] of Object.entries(counts?.[String(run.id)] || {})) {total += count;if (status === 'pending' || status === 'running') active += count;if (status === 'failed' || status === 'interrupted') failed += count;+ if (status === 'cancelled') cancelled += count;}}- return { total, active, failed, settled: total - active };+ return { total, active, failed, cancelled, settled: total - active };}/** 同一种任务连着派出的几轮合成一件事:自动修复每分钟派一批,一屏十几张「已完成」卡说的是同一件事。diff --git a/frontend/test/react/activity.test.tsx b/frontend/test/react/activity.test.tsxindex 9bb0afe54..4c1c03196 100644--- a/frontend/test/react/activity.test.tsx+++ b/frontend/test/react/activity.test.tsx@@ -96,6 +96,8 @@ function serve(...responses: (ActivityData | null)[]) {}const page = () => <QueryClientProvider client={queryClient}><ActivityPage /></QueryClientProvider>;+const controlButton = (name: string, root: ParentNode = document) =>+ root.querySelector<HTMLButtonElement>(`button[aria-label="${name}"]`);it('扫描各阶段已结束且留有问题时显示部分结果状态', async () => {serve(payload({ finished: [run({ task_key: 'library-processing', task_label: '扫描与采集',@@ -231,13 +233,13 @@ it('活动任务按服务端给出的动作暂停、继续和取消,并重新});await prefetchTasks(new AbortController().signal);const host = await mount(page());- await click(buttonNamed('暂停', host));- await vi.waitFor(() => expect(buttonNamed('继续', host)).not.toBeNull());+ await click(controlButton('暂停', host));+ await vi.waitFor(() => expect(controlButton('继续', host)).not.toBeNull());expect(host.querySelector('[data-run-id="1"]')?.textContent).toContain('已暂停');expect(host.querySelector('[role="progressbar"]')?.getAttribute('aria-valuenow')).toBe('3');- await click(buttonNamed('继续', host));- await vi.waitFor(() => expect(buttonNamed('暂停', host)).not.toBeNull());- await click(buttonNamed('取消', host));+ await click(controlButton('继续', host));+ await vi.waitFor(() => expect(controlButton('暂停', host)).not.toBeNull());+ await click(controlButton('取消', host));await vi.waitFor(() => expect(host.querySelector('[data-run-id="1"]')?.textContent).toContain('正在取消'));expect(host.textContent).not.toContain('已取消');expect(host.querySelector('[data-task-controls]')).toBeNull();@@ -248,6 +250,90 @@ it('活动任务按服务端给出的动作暂停、继续和取消,并重新]);});+it('主任务和后继使用带准确名称、提示和编辑键的图标控制', async () => {+ const child = followup(1, { status: 'running', finished_at: null,+ control: { state: 'paused', actions: ['resume', 'cancel'] } });+ const { host } = await open(payload({ running: [run({ control: { state: 'running', actions: ['pause', 'cancel'] } }), child] }));+ for (const [identity, labels] of [[1, ['暂停', '取消']], [90, ['继续', '取消']]] as const) {+ const controls = host.querySelector(`[data-task-controls="${identity}"]`)!;+ for (const label of labels) {+ const button = controlButton(label, controls)!;+ expect(button).not.toBeNull();+ expect(button.textContent).toBe('');+ expect(button.querySelector('svg')).not.toBeNull();+ expect(button.getAttribute('title')).toBe(label);+ expect(button.getAttribute('data-tooltip-copy-key')).toMatch(/^tasks\.control\.action\./);+ expect(button.hasAttribute('data-copy-key')).toBe(false);+ }+ }+});++it.each(['pause', 'resume'] as const)('取消优先于在途的 %s 请求,迟到回执不覆盖真实取消结果', async (action) => {+ const changeResponse = pending<{ ok: boolean; status: number; json: () => Promise<unknown> }>();+ const cancelResponse = pending<{ ok: boolean; status: number; json: () => Promise<unknown> }>();+ const posts: string[] = [];+ let current = run({ control: { state: action === 'pause' ? 'running' : 'paused', actions: [action, 'cancel'] } });+ stubFetch(async (_input, init) => {+ if (init?.method === 'POST') {+ const body = JSON.parse(String(init.body));+ posts.push(body.action);+ return body.action === 'cancel' ? cancelResponse.answer : changeResponse.answer;+ }+ return { ok: true, status: 200, json: async () => payload(current.status === 'cancelled'+ ? { finished: [current] } : { running: [current] }) };+ });+ await prefetchTasks(new AbortController().signal);+ const host = await mount(page());+ await click(controlButton(action === 'pause' ? '暂停' : '继续', host));+ expect(controlButton('取消', host)?.getAttribute('aria-disabled')).toBeNull();+ await click(controlButton('取消', host));+ expect(posts).toEqual([action, 'cancel']);+ current = { ...current, control: { state: 'cancelling', actions: [] } };+ await cancelResponse.release({ ok: true, status: 200, json: async () => ({ ok: true }) });+ await vi.waitFor(() => expect(host.querySelector('#run-1')?.textContent).toContain('正在取消'));+ expect(host.querySelector('#run-1')?.getAttribute('data-status')).toBe('running');+ current = { ...current, status: 'cancelled', control: undefined, finished_at: '2026-10-31T07:00:00Z' };+ await changeResponse.release({ ok: false, status: 409,+ json: async () => ({ message: '任务正在取消,不能再暂停或继续' }) });+ await vi.waitFor(() => expect(host.querySelector('#run-1')?.getAttribute('data-status')).toBe('cancelled'));+ expect(host.querySelector('#run-1')?.textContent).toContain('已取消');+ expect(host.querySelector('[data-task-control-feedback]')).toBeNull();+ expect(sections(host)).toContain('最近完成');+});++it('取消请求未被接受时,任务自然完成和原卡卸载后仍保留原因', async () => {+ const response = pending<{ ok: boolean; status: number; json: () => Promise<unknown> }>();+ let current = run({ control: { state: 'running', actions: ['pause', 'cancel'] } });+ stubFetch(async (_input, init) => {+ if (init?.method === 'POST') return response.answer;+ return { ok: true, status: 200, json: async () => payload(current.status === 'succeeded'+ ? { finished: [current] } : { running: [current] }) };+ });+ await prefetchTasks(new AbortController().signal);+ const host = await mount(page());+ await click(controlButton('取消', host));+ current = { ...current, status: 'succeeded', control: undefined, finished_at: '2026-10-31T07:00:00Z' };+ await act(async () => { await queryClient.invalidateQueries({ queryKey: ['tasks'] }) });+ expect(host.querySelector('[data-task-controls]')).toBeNull();+ await response.release({ ok: false, status: 409, json: async () => ({ message: '这轮任务已经结束' }) });+ await vi.waitFor(() => expect(host.querySelector('[data-task-control-feedback]')?.textContent).toContain('取消未完成'));+ expect(host.querySelector('[data-task-control-feedback]')?.textContent).toContain('这轮任务已经结束');+ expect(host.querySelector('#run-1')?.textContent).toContain('已完成');+ expect(host.querySelector('#run-1')?.textContent).not.toContain('已取消');+});++it('父任务的后继取消后在卡片上直接显示取消状态及数量', async () => {+ const parent = run({ status: 'succeeded', finished_at: '2026-10-31T07:00:00Z' });+ const child = followup(parent.id, { status: 'cancelled' });+ const { host } = await open(payload({ finished: [parent, child], followup_counts: { '1': { cancelled: 120 } } }));+ const card = host.querySelector('#run-1')!;+ expect(card.textContent).toContain('后续任务已取消');+ expect(card.textContent).toContain('后续任务已取消 120 项');+ expect(card.querySelector('details')?.open).toBe(false);+ expect(card.querySelector('[data-task-controls]')).toBeNull();+ expect(card.getAttribute('data-status')).toBe('succeeded');+});+it.each([['pausing', '正在暂停', ['resume', 'cancel']],['paused', '已暂停', ['resume', 'cancel']],@@ -257,8 +343,8 @@ it.each([control: { state, actions: [...actions] } })] }));expect(host.querySelector('[data-run-id="1"]')?.textContent).toContain(label);expect(host.querySelector('[role="status"]')).toBeNull();- expect(buttonNamed('暂停', host)).toBeNull();- expect(Boolean(buttonNamed('继续', host))).toBe(state !== 'cancelling');+ expect(controlButton('暂停', host)).toBeNull();+ expect(Boolean(controlButton('继续', host))).toBe(state !== 'cancelling');});it('任务控制请求等待时保持按钮焦点并阻止重复提交', async () => {@@ -274,14 +360,13 @@ it('任务控制请求等待时保持按钮焦点并阻止重复提交', async (});await prefetchTasks(new AbortController().signal);const host = await mount(page());- const pause = buttonNamed('暂停', host)!;+ const pause = controlButton('暂停', host)!;pause.focus();await click(pause);expect(pause.hasAttribute('disabled')).toBe(false);expect(pause.getAttribute('aria-busy')).toBe('true');expect(document.activeElement).toBe(pause);await click(pause);- await click(buttonNamed('取消', host));expect(posts).toEqual(['/api/tasks/1/control']);await response.release({ ok: true, status: 200, json: async () => ({ ok: true }) });});@@ -298,10 +383,10 @@ it('任务控制失败保留原状态和原因,可以在原位重试', async (});await prefetchTasks(new AbortController().signal);const host = await mount(page());- await click(buttonNamed('暂停', host));- expect(host.querySelector('[data-task-controls] [role="alert"]')?.textContent).toContain('任务已变化');- expect(buttonNamed('继续', host)).toBeNull();- await click(buttonNamed('暂停', host));+ await click(controlButton('暂停', host));+ await vi.waitFor(() => expect(host.querySelector('[data-task-control-feedback] [role="alert"]')?.textContent).toContain('任务已变化'));+ expect(controlButton('继续', host)).toBeNull();+ await click(controlButton('暂停', host));expect(attempts).toBe(2);});@@ -319,7 +404,7 @@ it('后继任务使用自身任务号控制,服务端未提供能力的父任expect(host.querySelector('[data-task-controls="1"]')).toBeNull();const controls = host.querySelector('[data-task-controls="90"]')!;expect(controls).not.toBeNull();- await click(buttonNamed('继续', controls));+ await click(controlButton('继续', controls));expect(posts).toEqual(['/api/tasks/90/control']);});@@ -343,12 +428,12 @@ it('父任务结束后仍可控制整批后继,未展示的后继也属于同await prefetchTasks(new AbortController().signal);const host = await mount(page());expect(host.querySelector('#run-1')?.textContent).toContain('列出其中 1 项');- await click(buttonNamed('暂停后续任务', host));- await vi.waitFor(() => expect(buttonNamed('继续后续任务', host)).not.toBeNull());+ await click(controlButton('暂停后续任务', host));+ await vi.waitFor(() => expect(controlButton('继续后续任务', host)).not.toBeNull());expect(host.querySelector('#run-1')?.textContent).toContain('已暂停');- await click(buttonNamed('继续后续任务', host));- await vi.waitFor(() => expect(buttonNamed('暂停后续任务', host)).not.toBeNull());- await click(buttonNamed('取消后续任务', host));+ await click(controlButton('继续后续任务', host));+ await vi.waitFor(() => expect(controlButton('暂停后续任务', host)).not.toBeNull());+ await click(controlButton('取消后续任务', host));await vi.waitFor(() => expect(host.querySelector('#run-1')?.textContent).toContain('正在取消'));expect(posts).toEqual([['/api/tasks/1/control', { action: 'pause' }],@@ -371,8 +456,8 @@ it('同类父任务有独立控制范围时分别显示,按钮只提交对应await prefetchTasks(new AbortController().signal);const host = await mount(page());expect(host.querySelectorAll('[data-task-key="follow-check"]')).toHaveLength(2);- await click(buttonNamed('继续后续任务', host.querySelector('#run-1')!));- await click(buttonNamed('暂停后续任务', host.querySelector('#run-2')!));+ await click(controlButton('继续后续任务', host.querySelector('#run-1')!));+ await click(controlButton('暂停后续任务', host.querySelector('#run-2')!));expect(posts).toEqual(['/api/tasks/1/control', '/api/tasks/2/control']);});@@ -512,8 +597,9 @@ it('后继挂在派出它的那一轮下面,不另占一张卡', async () => {expect(host.querySelectorAll('[data-task-key]')).toHaveLength(1);const row = host.querySelector('[data-followup-key]')!;expect(host.querySelector('[data-task-key=follow-check]')!.contains(row)).toBe(true);- expect([...row.querySelectorAll(':scope > span')].map((node) => node.textContent))- .toEqual(['补全资料图片', '已完成', '涼森れむ · 已保存资料图片']);+ expect(row.textContent).toContain('补全资料图片');+ expect(row.textContent).toContain('已完成');+ expect(row.textContent).toContain('涼森れむ · 已保存资料图片');expect(host.textContent).toContain('已安排 1 项补充任务');});@@ -554,8 +640,9 @@ it('后继还在跑时,派出它的那一轮整张卡留在正在进行,那const { host } = await open(payload({ running: [scraping], finished: [parent] }));expect(sections(host)).toEqual(['正在进行']);const row = host.querySelector('[data-followup-key]')!;- expect([...row.querySelectorAll(':scope > span')].map((node) => node.textContent))- .toEqual(['取新作资料', '进行中', 'MIZD-441 · 13 / 22 项']);+ expect(row.textContent).toContain('取新作资料');+ expect(row.textContent).toContain('进行中');+ expect(row.textContent).toContain('MIZD-441 · 13 / 22 项');});it('连着几轮什么也没发生的定时任务按种类各并成一张卡,有事的那一轮截断并单独摆', async () => {