Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix(tasks): 取消前复用确认弹窗并保留提示编辑

longmeidao1bf225e2eb66
diff --git a/frontend/e2e/tooltip-fidelity.test.ts b/frontend/e2e/tooltip-fidelity.test.ts
index 1fe58c7ba..da824a920 100644
--- a/frontend/e2e/tooltip-fidelity.test.ts
+++ b/frontend/e2e/tooltip-fidelity.test.ts
@@ -1,4 +1,5 @@
import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
import { after, before, describe, it } from 'node:test';
import type { Browser } from 'playwright-core';
import { launch, VIEWPORTS } from './harness.ts';
@@ -115,5 +116,62 @@ describe('共享提示的文字与锚点', () => {
assert.equal(await tip.getAttribute('data-copy-key'), 'tasks.control.action.followups.pause');
} finally { await opened.close() }
});
+ it(`${viewport.name} 提示在选择文案来源和编辑子节点期间保持可见,Esc先取消编辑`, async () => {
+ const opened = await openItemPage(browser, '/', viewport, { ready: '[data-catalog-frame]' });
+ try {
+ await opened.page.addScriptTag({ content: await readFile(new URL('../src/copy-editor-core.js', import.meta.url), 'utf8') });
+ await opened.page.evaluate(() => {
+ const button = document.createElement('button');
+ button.id = 'tip-edit-action'; button.title = '继续'; button.setAttribute('aria-label', '继续');
+ button.dataset.tooltipCopyKey = 'tasks.control.action.resume';
+ button.style.cssText = 'position:fixed;left:120px;top:240px;z-index:9999;width:32px;height:32px';
+ button.innerHTML = '<svg width="16" height="16"><path d="M4 2v12l10-6Z"/></svg>';
+ document.body.append(button);
+ const core = (globalThis as any).PeachCopyEditorCore;
+ const tools = core.createTools({ onToggle() {}, onExport() {}, onExit() {} });
+ core.create({
+ highlight: tools.highlight,
+ resolve(node: Text) { return node.parentElement?.closest('#board-control-tooltip') ? {} : null; },
+ onBusy: tools.setBusy,
+ onStatus: tools.say,
+ async prepare(edit: any) {
+ const range = document.createRange(); range.selectNodeContents(edit.node);
+ const candidate = await tools.choose([
+ { label: 'task-controls.tsx', value: { source: 'task-controls.tsx' } },
+ { label: 'other.tsx', value: { source: 'other.tsx' } },
+ ], range.getBoundingClientRect(), { label: '文案来源' });
+ return candidate ? { candidate } : null;
+ },
+ async save(_edit: any, replacement: string) { return { text: replacement }; },
+ });
+ });
+ await opened.page.locator('#tip-edit-action').hover();
+ const tip = opened.page.locator('#board-control-tooltip');
+ await tip.waitFor({ state: 'visible' });
+ await tip.click();
+ const choice = opened.page.locator('[data-copy-choice]');
+ await choice.waitFor({ state: 'visible' });
+ assert.equal(await tip.isVisible(), true);
+ assert.equal(await tip.getAttribute('data-copy-key'), 'tasks.control.action.resume');
+ await choice.selectOption('0');
+ const input = tip.locator('[data-copy-inline][aria-label="修改文字"]');
+ await input.waitFor({ state: 'visible' });
+ await input.fill('临时继续');
+ await input.press('Escape');
+ assert.equal(await tip.locator('[data-copy-inline]').count(), 0);
+ assert.equal(await tip.isVisible(), true);
+ assert.equal(await tip.textContent(), '继续');
+ assert.equal(await tip.getAttribute('data-copy-key'), 'tasks.control.action.resume');
+ await opened.page.keyboard.press('Escape');
+ await tip.waitFor({ state: 'hidden' });
+ await opened.page.locator('#tip-edit-action').hover();
+ await tip.waitFor({ state: 'visible' });
+ await tip.click();
+ await choice.waitFor({ state: 'visible' });
+ await choice.press('Escape');
+ await choice.waitFor({ state: 'detached' });
+ assert.equal(await tip.isVisible(), true);
+ } finally { await opened.close() }
+ });
}
});
diff --git a/frontend/src/board-tooltip.ts b/frontend/src/board-tooltip.ts
index 35733fc2d..912674cb3 100644
--- a/frontend/src/board-tooltip.ts
+++ b/frontend/src/board-tooltip.ts
@@ -57,7 +57,11 @@ export function initBoardTooltip() {
let target: HTMLElement | null = null, title = '', described: string | null = null;
let timer: ReturnType<typeof setTimeout> | undefined;
let exitTimer: ReturnType<typeof setTimeout> | undefined;
+ let enteringEditor = false;
const editableTip = () => tip.hasAttribute('data-copy-key') && Boolean(document.querySelector('[data-copy-bar]'));
+ const editingTip = () => editableTip() && (enteringEditor
+ || Boolean(tip.querySelector('[data-copy-inline],[contenteditable]'))
+ || Boolean(document.querySelector('[data-copy-choice],[data-copy-bar][aria-busy="true"]')));
const place = (next: HTMLElement) => {
const rect = anchorRect(next), box = tip.getBoundingClientRect();
if (!rect) return;
@@ -65,7 +69,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); clearTimeout(exitTimer);
+ clearTimeout(exitTimer);
+ if (editingTip()) return;
+ clearTimeout(timer);
if (tip.matches(':popover-open')) tip.hidePopover(); tip.hidden = true;
tip.removeAttribute('data-copy-key');
if (target) {
@@ -76,6 +82,7 @@ export function initBoardTooltip() {
target = null;
};
const show = (node: EventTarget | null, delay: number) => {
+ if (editingTip()) return;
if (!(node instanceof Element)) return;
const next = node.closest<HTMLElement>('[title]');
if (target?.contains(node) && (!next || next.contains(target))) return;
@@ -105,16 +112,22 @@ export function initBoardTooltip() {
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;
+ if (tip.contains(event.relatedTarget as Node | null) || editingTip()) return;
clearTimeout(exitTimer); exitTimer = setTimeout(hide, 250);
} else hide();
});
+ document.addEventListener('pointerdown', event => {
+ if (!editableTip() || !tip.contains(event.target as Node)) return;
+ enteringEditor = true;
+ clearTimeout(exitTimer);
+ setTimeout(() => { enteringEditor = false }, 0);
+ }, true);
document.addEventListener('focusin', event => show(event.target, 0));
document.addEventListener('focusout', event => {
- if (editableTip() && (tip.contains(event.relatedTarget as Node | null) || tip.hasAttribute('data-copy-inline'))) return;
+ if (editableTip() && (tip.contains(event.relatedTarget as Node | null) || editingTip())) return;
hide();
});
- document.addEventListener('keydown', event => { if (event.key === 'Escape') hide() });
+ document.addEventListener('keydown', event => { if (event.key === 'Escape' && !editingTip()) hide() });
document.addEventListener('scroll', event => {
if (!target || !scrollMovesAnchor(event, target)) return;
const rect = anchorRect(target);
diff --git a/frontend/src/react/activity/task-controls.tsx b/frontend/src/react/activity/task-controls.tsx
index d06d910bb..c1fce19c9 100644
--- a/frontend/src/react/activity/task-controls.tsx
+++ b/frontend/src/react/activity/task-controls.tsx
@@ -2,6 +2,7 @@
import { useRef } from 'react';
import { RiPauseLine, RiPlayLine, RiStopLine } from '@remixicon/react';
import { useMutation, useMutationState, useQueryClient } from '@tanstack/react-query';
+import { confirmModal } from '@peach/legacy/ui';
import { Button } from '@/components/base/buttons/button';
@@ -47,7 +48,7 @@ export function TaskControlFeedback() {
export function TaskControls({ run }: { run: TaskRunPayload }) {
const client = useQueryClient();
- const pending = useRef({ change: false, cancel: false });
+ const pending = useRef({ change: false, cancel: false, confirmation: false });
const refresh = () => { void client.invalidateQueries({ queryKey: TASKS_KEY }) };
const send = (command: ControlCommand) => controlTask(command.id, command.action);
const change = useMutation({
@@ -68,9 +69,22 @@ export function TaskControls({ run }: { run: TaskRunPayload }) {
const submit = (action: TaskControlAction) => {
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);
+ if (pending.current.cancel || pending.current.confirmation || cancellation.isSuccess) return;
+ pending.current.confirmation = true;
+ void confirmModal({
+ title: followups ? `取消「${run.task_label}」的全部后续任务` : `取消任务「${run.task_label}」`,
+ body: followups
+ ? '将停止这轮已派出的全部后续任务,包括正在处理和排队的项目。已保存的资料和结果会保留。'
+ + '这批后续任务取消后不能继续,需要时重新发起。'
+ : '将停止这轮剩余的处理及其后续任务。已保存的资料和结果会保留。'
+ + '这轮任务取消后不能继续,需要时重新发起。',
+ confirmLabel: followups ? '取消后续任务' : '取消任务',
+ danger: true,
+ onConfirm: async () => {
+ pending.current.cancel = true;
+ return await cancellation.mutateAsync(command);
+ },
+ }).finally(() => { pending.current.confirmation = false });
} else {
if (pending.current.change || pending.current.cancel || cancelling) return;
pending.current.change = true;
diff --git a/frontend/test/react/activity.test.tsx b/frontend/test/react/activity.test.tsx
index 4c1c03196..0db6157da 100644
--- a/frontend/test/react/activity.test.tsx
+++ b/frontend/test/react/activity.test.tsx
@@ -98,6 +98,7 @@ 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}"]`);
+const confirmTaskCancellation = () => click(document.querySelector('[data-modal-confirm]'));
it('扫描各阶段已结束且留有问题时显示部分结果状态', async () => {
serve(payload({ finished: [run({ task_key: 'library-processing', task_label: '扫描与采集',
@@ -240,6 +241,7 @@ it('活动任务按服务端给出的动作暂停、继续和取消,并重新
await click(controlButton('继续', host));
await vi.waitFor(() => expect(controlButton('暂停', host)).not.toBeNull());
await click(controlButton('取消', host));
+ await confirmTaskCancellation();
await vi.waitFor(() => expect(host.querySelector('[data-run-id="1"]')?.textContent).toContain('正在取消'));
expect(host.textContent).not.toContain('已取消');
expect(host.querySelector('[data-task-controls]')).toBeNull();
@@ -268,6 +270,77 @@ it('主任务和后继使用带准确名称、提示和编辑键的图标控制'
}
});
+it('取消任务先复用确认框,初始聚焦取消,未确认或关闭弹窗都不提交', async () => {
+ const posts: unknown[] = [];
+ const current = run({ control: { state: 'running', actions: ['pause', 'cancel'] } });
+ stubFetch(async (_input, init) => {
+ if (init?.method === 'POST') posts.push(JSON.parse(String(init.body)));
+ return { ok: true, status: 200, json: async () => payload({ running: [current] }) };
+ });
+ await prefetchTasks(new AbortController().signal);
+ const host = await mount(page());
+ await click(controlButton('取消', host));
+ const dialog = document.querySelector<HTMLDialogElement>('dialog')!;
+ expect(dialog.open).toBe(true);
+ expect(dialog.querySelector('h3')?.textContent).toBe('取消任务「追更检查」');
+ expect(dialog.textContent).toContain('已保存的资料和结果会保留');
+ expect(dialog.textContent).toContain('取消后不能继续');
+ expect(document.activeElement).toBe(dialog.querySelector('[data-modal-cancel]'));
+ expect(posts).toEqual([]);
+ await click(dialog.querySelector('[data-modal-cancel]'));
+ expect(document.querySelector('dialog')).toBeNull();
+ expect(posts).toEqual([]);
+ await click(controlButton('取消', host));
+ await confirmTaskCancellation();
+ await vi.waitFor(() => expect(posts).toEqual([{ action: 'cancel' }]));
+ await vi.waitFor(() => expect(document.querySelector('dialog')).toBeNull());
+});
+
+it('确认取消的请求忙态阻止重复提交,失败留在弹窗内供重试', async () => {
+ const answer = pending<{ ok: boolean; status: number; json: () => Promise<unknown> }>();
+ let attempts = 0;
+ const current = run({ control: { state: 'running', actions: ['pause', 'cancel'] } });
+ stubFetch(async (_input, init) => {
+ if (init?.method === 'POST') {
+ attempts += 1;
+ return attempts === 1 ? answer.answer : { ok: true, status: 200, json: async () => ({ ok: true }) };
+ }
+ return { ok: true, status: 200, json: async () => payload({ running: [current] }) };
+ });
+ await prefetchTasks(new AbortController().signal);
+ const host = await mount(page());
+ await click(controlButton('取消', host));
+ const dialog = document.querySelector<HTMLDialogElement>('dialog')!;
+ const confirm = dialog.querySelector<HTMLButtonElement>('[data-modal-confirm]')!;
+ await click(confirm);
+ expect(confirm.getAttribute('aria-busy')).toBe('true');
+ expect(confirm.hasAttribute('disabled')).toBe(false);
+ await click(confirm);
+ await click(dialog.querySelector('[data-modal-cancel]'));
+ expect(attempts).toBe(1);
+ expect(dialog.open).toBe(true);
+ await answer.release({ ok: false, status: 409, json: async () => ({ message: '任务暂时无法停止' }) });
+ await vi.waitFor(() => expect(dialog.querySelector('[data-modal-error]')?.textContent).toContain('任务暂时无法停止'));
+ expect(dialog.open).toBe(true);
+ await click(confirm);
+ await vi.waitFor(() => expect(attempts).toBe(2));
+ await vi.waitFor(() => expect(document.querySelector('dialog')).toBeNull());
+});
+
+it('已结束父任务的取消确认明确覆盖全部正在处理和排队的后继', async () => {
+ const parent = run({ status: 'succeeded', control: { state: 'paused', actions: ['resume', 'cancel'] } });
+ const child = followup(1, { status: 'pending', finished_at: null });
+ const { fetcher, host } = await open(payload({ running: [child], finished: [parent],
+ followup_counts: { '1': { pending: 1200 } } }));
+ await click(controlButton('取消后续任务', host));
+ const dialog = document.querySelector<HTMLDialogElement>('dialog')!;
+ expect(dialog.querySelector('h3')?.textContent).toBe('取消「追更检查」的全部后续任务');
+ expect(dialog.textContent).toContain('全部后续任务,包括正在处理和排队的项目');
+ expect(dialog.querySelector('[data-modal-confirm]')?.textContent).toBe('取消后续任务');
+ expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(0);
+ await click(dialog.querySelector('[data-modal-cancel]'));
+});
+
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> }>();
@@ -287,6 +360,8 @@ it.each(['pause', 'resume'] as const)('取消优先于在途的 %s 请求,迟
await click(controlButton(action === 'pause' ? '暂停' : '继续', host));
expect(controlButton('取消', host)?.getAttribute('aria-disabled')).toBeNull();
await click(controlButton('取消', host));
+ expect(posts).toEqual([action]);
+ await confirmTaskCancellation();
expect(posts).toEqual([action, 'cancel']);
current = { ...current, control: { state: 'cancelling', actions: [] } };
await cancelResponse.release({ ok: true, status: 200, json: async () => ({ ok: true }) });
@@ -312,6 +387,7 @@ it('取消请求未被接受时,任务自然完成和原卡卸载后仍保留
await prefetchTasks(new AbortController().signal);
const host = await mount(page());
await click(controlButton('取消', host));
+ await confirmTaskCancellation();
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();
@@ -434,6 +510,7 @@ it('父任务结束后仍可控制整批后继,未展示的后继也属于同
await click(controlButton('继续后续任务', host));
await vi.waitFor(() => expect(controlButton('暂停后续任务', host)).not.toBeNull());
await click(controlButton('取消后续任务', host));
+ await confirmTaskCancellation();
await vi.waitFor(() => expect(host.querySelector('#run-1')?.textContent).toContain('正在取消'));
expect(posts).toEqual([
['/api/tasks/1/control', { action: 'pause' }],