Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(tasks): 显示三色实测资源读数并标红已取消状态

longmeidao636f828487ea
diff --git a/frontend/e2e/design-activity.test.ts b/frontend/e2e/design-activity.test.ts
index b5d79128b..6733547b0 100644
--- a/frontend/e2e/design-activity.test.ts
+++ b/frontend/e2e/design-activity.test.ts
@@ -1,12 +1,74 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import type { Browser } from 'playwright-core';
-import { installDesignBrowser, PIXEL } from './design-fixture.ts';
+import { installDesignBrowser, PIXEL, tokenColor } from './design-fixture.ts';
import { requiredEnv, settle, visit, VIEWPORTS } from './harness.ts';
describe('任务页云下载布局', () => {
let browser: Browser;
installDesignBrowser((next) => { browser = next; });
+ for (const viewport of VIEWPORTS) it(`${viewport.name} 资源分色并在高占用时加深,已取消使用红色标签`, async () => {
+ const reading = (high: boolean) => ({
+ cpu: { state: 'ready', percent: high ? 75 : 5, high },
+ gpu: { state: 'ready', percent: high ? 80 : 4, high },
+ network: { state: 'ready', bytes_per_second: high ? 15 * 1024 * 1024 : 1024, high },
+ sampled_at: '2026-10-31T08:00:00Z',
+ });
+ const row = (id: number, status: string) => ({
+ id, task_key: `resource-${id}`, task_label: `资源采样任务 ${id}`, trigger: 'manual', status,
+ host: 'desk', started_at: '2026-10-31T08:00:00Z',
+ finished_at: status === 'running' ? null : '2026-10-31T08:01:00Z',
+ elapsed_seconds: 60, progress_current: 1, progress_total: 10, progress_label: '正在处理',
+ result_summary: {}, error: '', parent_run_id: null as number | null, followup_key: '',
+ });
+ const opened = await visit(browser, '/tasks', viewport, async page => {
+ await page.route('**/api/downloads?*', route => route.fulfill({ json: { available: false, tasks: [], providers: [] } }));
+ await page.route('**/api/tasks*', route => route.fulfill({ json: {
+ available: true, running: [
+ { ...row(1, 'running'), resources: reading(true), control: { state: 'running', actions: ['pause', 'cancel'] } },
+ { ...row(90, 'running'), parent_run_id: 1, followup_key: 'child:90', resources: reading(false),
+ control: { state: 'running', actions: ['pause', 'cancel'] } },
+ ], skipped: [], finished: [row(3, 'cancelled'), row(4, 'succeeded'), row(5, 'succeeded')],
+ followup_counts: { 4: { cancelled: 2 }, 5: { succeeded: 1, cancelled: 1 } },
+ } }));
+ });
+ try {
+ const page = opened.page;
+ await page.locator('[data-task-resources="1"]').waitFor();
+ const pairs = [['cpu', 'blue'], ['gpu', 'purple'], ['network', 'cyan']] as const;
+ const backgrounds: string[] = [];
+ for (const [metric, color] of pairs) {
+ const high = page.locator(`[data-task-resources="1"] [data-task-resource="${metric}"]`);
+ const normal = page.locator(`[data-task-resources="90"] [data-task-resource="${metric}"]`);
+ const normalBackground = await normal.evaluate(node => getComputedStyle(node).backgroundColor);
+ const highBackground = await high.evaluate(node => getComputedStyle(node).backgroundColor);
+ assert.equal(normalBackground, await tokenColor(page, 'body', `--color-status-${color}-background`));
+ assert.equal(highBackground, await tokenColor(page, 'body', `--color-status-${color}-text`));
+ assert.notEqual(highBackground, normalBackground);
+ backgrounds.push(highBackground);
+ }
+ assert.equal(new Set(backgrounds).size, 3);
+ const red = await tokenColor(page, 'body', '--color-status-rose-background');
+ for (const [id, label] of [[3, '已取消'], [4, '后续任务已取消'], [5, '部分后续任务已取消']] as const) {
+ const badge = page.locator(`#run-${id}`).getByText(label, { exact: true });
+ const color = await badge.evaluate(node => {
+ const chip = node.parentElement?.tagName === 'SPAN' ? node.parentElement : node;
+ return getComputedStyle(chip).backgroundColor;
+ });
+ assert.equal(color, red);
+ }
+ const geometry = await page.locator('#run-1').evaluate(card => {
+ const controls = card.querySelector('[data-task-controls="1"]')!.getBoundingClientRect();
+ const title = card.querySelector('strong')!.getBoundingClientRect();
+ return { fits: document.documentElement.scrollWidth <= innerWidth,
+ rightOfTitle: controls.left >= title.right, insideCard: controls.right <= card.getBoundingClientRect().right };
+ });
+ assert.equal(geometry.fits, true);
+ assert.equal(geometry.rightOfTitle, true);
+ assert.equal(geometry.insideCard, true);
+ assert.deepEqual(opened.problems, []);
+ } finally { await opened.close() }
+ });
for (const viewport of VIEWPORTS) it(`${viewport.name} 追更问题展示来源原因和管理入口`, async () => {
const opened = await visit(browser, '/tasks', viewport, async page => {
await page.route('**/api/tasks*', route => route.fulfill({ json: {
diff --git a/frontend/src/react/activity/activity-page.tsx b/frontend/src/react/activity/activity-page.tsx
index b4fd266ad..f659fa230 100644
--- a/frontend/src/react/activity/activity-page.tsx
+++ b/frontend/src/react/activity/activity-page.tsx
@@ -35,6 +35,7 @@ import { BackgroundIssues } from './background-issues';
import { DownloadsPanel } from './downloads-panel';
import { ErrorDetails, ErrorExcerpt } from './error-excerpt';
import { TaskControlFeedback, TaskControls } from './task-controls';
+import { TaskResources } from './task-resources';
import {
elapsedText, fetchEarlier, fetchTasks, foldByKind, foldRoutine, followupDetail, followupTally, groupFollowups, isActive,
hasResultProblems, isRoutine, latestOfKind, mergeFinished, momentText, pollInterval, problemDestination, progressText,
@@ -46,9 +47,9 @@ const FOLLOWUP_ROWS = 50;
/** 自己只负责派发后继的任务:一轮只是「安排了几项」,要看的是那几项的结果。 */
const DISPATCHERS = new Set(['upgrade-repairs']);
-/* 完成绿、失败红、进行中蓝、意外中断黄,主动取消和排队为中性。 */
+/* 完成绿、失败与已取消红、进行中蓝、意外中断黄,排队为中性。 */
const BADGE_COLORS: Record<string, 'lime' | 'rose' | 'yellow' | 'blue' | 'neutral'> = {
- succeeded: 'lime', failed: 'rose', cancelled: 'neutral', interrupted: 'yellow', running: 'blue', pending: 'neutral',
+ succeeded: 'lime', failed: 'rose', cancelled: 'rose', interrupted: 'yellow', running: 'blue', pending: 'neutral',
};
const CONTROL_LABELS: Record<TaskControlState, string> = {
@@ -95,6 +96,7 @@ function FollowupList({ rows }: { rows: TaskRunPayload[] }) {
</div>
<TaskControls run={row} />
</div>
+ <TaskResources run={row} />
{/* 排队中的那些还没有结果:空的「技术详情」展开只有一对花括号。 */}
{Object.keys(row.result_summary || {}).length
? <div className="w-full min-w-0">
@@ -114,9 +116,9 @@ function FollowupList({ rows }: { rows: TaskRunPayload[] }) {
/** 一轮任务一张卡。失败时整张卡的框线换成 danger 色,不给结束原因那行字上色——
* 一屏十几行里逐行读红字,比看一眼哪张卡的框是红的慢得多。 */
function RunCard(
- { run, meta, children, footer, followups, followupTotal = 0, badge }:
+ { run, meta, children, footer, followups, followupTotal = 0, badge, resourceActive }:
{ run: TaskRunPayload; meta: string; children?: ReactNode; footer?: string;
- followups?: TaskRunPayload[]; followupTotal?: number; badge?: ReactNode },
+ followups?: TaskRunPayload[]; followupTotal?: number; badge?: ReactNode; resourceActive?: boolean },
) {
/* 一轮派出上千条后继时只下发最近几十条,合并的几批又可能各带几十条:标题写全数,
列表先列在跑与排队的、再列最近结束的,最多 `FOLLOWUP_ROWS` 条,并说清只列了其中几条。 */
@@ -144,6 +146,7 @@ function RunCard(
<TaskControls run={run} />
</div>
<p className="text-caption-1-regular text-text-secondary">{meta}</p>
+ <TaskResources run={run} active={resourceActive} />
{children}
</div>
{shown ? <div className="border-t border-separator-border px-5 py-2.5">
@@ -221,7 +224,7 @@ function SettledRun(
return (
<RunCard run={run} meta={meta} footer={run.error} followups={followups} followupTotal={followupTotal}
badge={followupCancelled && run.status === 'succeeded'
- ? <Chip color="neutral"><span data-copy-key={`tasks.followups.cancelled.${followupCancelled === followupTotal ? 'all' : 'partial'}`}>
+ ? <Chip color="rose"><span data-copy-key={`tasks.followups.cancelled.${followupCancelled === followupTotal ? 'all' : 'partial'}`}>
{followupCancelled === followupTotal ? '后续任务已取消' : '部分后续任务已取消'}
</span></Chip>
: batches && followupFailed ? <Chip color="yellow">发现问题</Chip> : undefined}>
@@ -273,7 +276,7 @@ function WorkingRun(
runs.length > 1 ? `${runs.length} 批` : '',
`${momentText(oldest.started_at || oldest.finished_at)} 开始`].filter(Boolean).join(' · ');
return (
- <RunCard run={run} meta={meta} followups={followups} followupTotal={total}
+ <RunCard run={run} meta={meta} followups={followups} followupTotal={total} resourceActive
badge={run.control ? <StatusBadge run={run} /> : <Chip color="blue">进行中</Chip>}>
<div className="flex flex-col gap-1.5">
<Progress label={`${run.task_label}进度`} value={settled} max={total} />
diff --git a/frontend/src/react/activity/task-resources.tsx b/frontend/src/react/activity/task-resources.tsx
new file mode 100644
index 000000000..1294de690
--- /dev/null
+++ b/frontend/src/react/activity/task-resources.tsx
@@ -0,0 +1,52 @@
+/* 每轮任务的实测读数。高占用仅改变 Chip 强调程度,不调整任务资源使用。 */
+import { fmtSize } from '@peach/legacy/core';
+import { Chip } from '@/components/base/badges/chip';
+
+import { isActive, type TaskResourceState, type TaskRunPayload } from './tasks';
+
+const METRICS = {
+ cpu: {
+ name: 'CPU', color: 'blue', high: 'bg-status-blue-text text-background-primary-default',
+ description: 'CPU 使用率以本机总计算容量为 100%。达到 50% 时加深显示。',
+ },
+ gpu: {
+ name: 'GPU', color: 'purple', high: 'bg-status-purple-text text-background-primary-default',
+ description: 'GPU 使用率显示该任务最忙的 GPU 引擎。达到 50% 时加深显示。',
+ },
+ network: {
+ name: '网络', color: 'cyan', high: 'bg-status-cyan-text text-background-primary-default',
+ description: '网络速率是该任务实测传输量,达到 10 MiB/s 时加深显示。挂载盘或无法准确归属的传输显示未取得。',
+ },
+} as const;
+
+function unavailable(state: TaskResourceState) {
+ return state === 'sampling' ? '采样中' : '未取得';
+}
+
+export function TaskResources({ run, active = isActive(run) || Boolean(run.control) }: {
+ run: TaskRunPayload; active?: boolean;
+}) {
+ if (!active || !run.resources) return null;
+ const resources = run.resources;
+ return <div data-task-resources={run.id} className="flex min-w-0 flex-wrap items-center gap-2">
+ {(['cpu', 'gpu', 'network'] as const).map((key) => {
+ const metric = resources[key];
+ const appearance = METRICS[key];
+ const value = key === 'network' ? resources.network.bytes_per_second : resources[key].percent;
+ const ready = metric.state === 'ready' && value !== null;
+ const high = ready && metric.high;
+ const label = ready
+ ? key === 'network' ? `${fmtSize(value)}/s` : `${value.toLocaleString(undefined, { maximumFractionDigits: 1 })}%`
+ : unavailable(metric.state);
+ const explanation = [metric.reason, high ? '当前为高占用。' : '', appearance.description, resources.detail]
+ .filter(Boolean).join('\n');
+ return <Chip key={key} variant="caption" color={appearance.color}
+ className={high ? appearance.high : undefined} tabIndex={0} title={explanation}
+ data-task-resource={key} data-resource-state={metric.state} data-resource-high={high || undefined}
+ data-copy-ignore=""
+ data-tooltip-copy-key={!metric.reason && !resources.detail && !high ? `tasks.resources.${key}.description` : undefined}>
+ {appearance.name} {label}
+ </Chip>;
+ })}
+ </div>;
+}
diff --git a/frontend/src/react/activity/tasks.ts b/frontend/src/react/activity/tasks.ts
index bfbc156fd..350f1f410 100644
--- a/frontend/src/react/activity/tasks.ts
+++ b/frontend/src/react/activity/tasks.ts
@@ -13,6 +13,16 @@ export const TASKS_KEY = ['tasks'] as const;
export type TaskControlAction = 'pause' | 'resume' | 'cancel';
export type TaskControlState = 'running' | 'pausing' | 'paused' | 'cancelling';
+export type TaskResourceState = 'ready' | 'sampling' | 'unavailable';
+export interface TaskResourceMetric { state: TaskResourceState; high: boolean; reason?: string }
+export interface TaskPercentMetric extends TaskResourceMetric { percent: number | null }
+export interface TaskResourcesPayload {
+ cpu: TaskPercentMetric;
+ gpu: TaskPercentMetric;
+ network: TaskResourceMetric & { bytes_per_second: number | null };
+ sampled_at: string;
+ detail?: string;
+}
export interface TaskRunPayload {
id: number;
@@ -37,6 +47,8 @@ export interface TaskRunPayload {
followup_depth: number;
/** 服务端给出当前控制状态与可用动作,界面不按任务种类推断。 */
control?: { state: TaskControlState; actions: TaskControlAction[] };
+ /** 只投影可归属的实测读数;缺失字段代表该快照未提供资源采样。 */
+ resources?: TaskResourcesPayload;
}
export interface ActivityData {
diff --git a/frontend/test/react/activity.test.tsx b/frontend/test/react/activity.test.tsx
index 0db6157da..240467b69 100644
--- a/frontend/test/react/activity.test.tsx
+++ b/frontend/test/react/activity.test.tsx
@@ -13,7 +13,7 @@ import { ErrorExcerpt } from '../../src/react/activity/error-excerpt';
import {
elapsedText, errorHeadline, followupDetail, hasResultProblems, isRoutine, prefetchTasks, progressText, summaryItems, summaryText, TASKS_URL,
} from '../../src/react/activity/tasks';
-import type { ActivityData, FinishedPage, TaskRunPayload } from '../../src/react/activity/tasks';
+import type { ActivityData, FinishedPage, TaskResourcesPayload, TaskRunPayload } from '../../src/react/activity/tasks';
import type { DownloadsSnapshot } from '../../src/react/bundle';
import { queryClient } from '../../src/react/query';
@@ -61,6 +61,12 @@ const followup = (parent: number, overrides: Partial<TaskRunPayload> = {}): Task
const payload = (overrides: Partial<ActivityData> = {}): ActivityData => ({
available: true, running: [], skipped: [], finished: [], ...overrides,
});
+const resources = (overrides: Partial<TaskResourcesPayload> = {}): TaskResourcesPayload => ({
+ cpu: { state: 'ready', percent: 12.5, high: false },
+ gpu: { state: 'ready', percent: 0, high: false },
+ network: { state: 'ready', bytes_per_second: 2 * 1024 * 1024, high: false },
+ sampled_at: '2026-10-31T08:00:00Z', ...overrides,
+});
/* 云下载段自己取 `/api/downloads`,「需要处理」自己取 `/api/background-issues`。这里的用例只数
任务中心的请求,那两路另答:云下载回空表、后台问题回 `issues` 当前那一份(默认没有),两段就不画。 */
@@ -217,6 +223,72 @@ it('总量未知时不画假进度条,只说正在做什么', async () => {
expect(host.querySelector('[role=status]')?.textContent).toContain('正在查第三个来源');
});
+it('活动主任务和后继持续显示各自的CPU、GPU与实测网速', async () => {
+ const child = followup(1, { status: 'running', resources: resources({
+ cpu: { state: 'ready', percent: 3, high: false },
+ network: { state: 'ready', bytes_per_second: 1024, high: false },
+ }) });
+ const { host } = await open(payload({ running: [run({ resources: resources() }), child] }));
+ const main = host.querySelector('[data-task-resources="1"]')!;
+ const nested = host.querySelector('[data-task-resources="90"]')!;
+ expect(main.querySelector('[data-task-resource="cpu"]')?.textContent).toBe('CPU 12.5%');
+ expect(main.querySelector('[data-task-resource="gpu"]')?.textContent).toBe('GPU 0%');
+ expect(main.querySelector('[data-task-resource="network"]')?.textContent).toBe('网络 2 MB/s');
+ expect(nested.querySelector('[data-task-resource="cpu"]')?.textContent).toBe('CPU 3%');
+ expect(nested.querySelector('[data-task-resource="network"]')?.textContent).toBe('网络 1 KB/s');
+ expect(main.querySelector('[data-task-resource="cpu"]')?.getAttribute('title')).toContain('本机总计算容量');
+ expect(main.querySelector('[data-task-resource="gpu"]')?.getAttribute('title')).toContain('最忙的 GPU 引擎');
+ expect(main.querySelector('[data-task-resource="network"]')?.getAttribute('title')).toContain('该任务实测传输量');
+ expect([...main.querySelectorAll('[data-task-resource]')].every(node => node.getAttribute('tabindex') === '0')).toBe(true);
+});
+
+it('资源采样中和未取得分别显示,原因优先说明,不把null填成零', async () => {
+ const { host } = await open(payload({ running: [run({ resources: resources({
+ cpu: { state: 'sampling', percent: null, high: false, reason: '正在建立采样基线' },
+ gpu: { state: 'unavailable', percent: null, high: false, reason: '当前系统无法归属GPU引擎' },
+ network: { state: 'unavailable', bytes_per_second: null, high: false, reason: '挂载盘传输无法准确归属' },
+ }) })] }));
+ const metrics = host.querySelector('[data-task-resources="1"]')!;
+ expect(metrics.querySelector('[data-task-resource="cpu"]')?.textContent).toBe('CPU 采样中');
+ expect(metrics.querySelector('[data-task-resource="gpu"]')?.textContent).toBe('GPU 未取得');
+ expect(metrics.querySelector('[data-task-resource="network"]')?.textContent).toBe('网络 未取得');
+ expect(metrics.textContent).not.toContain('0%');
+ expect(metrics.textContent).not.toContain('0 B/s');
+ expect(metrics.querySelector('[data-task-resource="network"]')?.getAttribute('title')).toMatch(/^挂载盘传输无法准确归属/);
+});
+
+it('真实零读数可见,高占用由该指标的真实high状态强调', async () => {
+ const { host } = await open(payload({ running: [run({ resources: resources({
+ cpu: { state: 'ready', percent: 0, high: false },
+ gpu: { state: 'ready', percent: 70.1, high: true },
+ network: { state: 'ready', bytes_per_second: 0, high: false },
+ }) })] }));
+ const metrics = host.querySelector('[data-task-resources="1"]')!;
+ expect(metrics.querySelector('[data-task-resource="cpu"]')?.textContent).toBe('CPU 0%');
+ expect(metrics.querySelector('[data-task-resource="network"]')?.textContent).toBe('网络 0 B/s');
+ const gpu = metrics.querySelector('[data-task-resource="gpu"]')!;
+ expect(gpu.textContent).toBe('GPU 70.1%');
+ expect(gpu.getAttribute('title')).toContain('当前为高占用');
+ expect(gpu.getAttribute('data-resource-high')).toBe('true');
+ expect(metrics.querySelector('[data-task-resource="cpu"]')?.hasAttribute('data-resource-high')).toBe(false);
+});
+
+it('父任务已结束而后继仍在活动时展示后端聚合读数,历史终态不展示旧采样', async () => {
+ const parent = run({ id: 1, status: 'succeeded', resources: resources({ detail: '统计这轮仍在活动的全部后继' }) });
+ const historical = run({ id: 2, status: 'cancelled', resources: resources() });
+ const { host } = await open(payload({ running: [followup(1, { status: 'pending' })],
+ finished: [parent, historical], followup_counts: { '1': { pending: 100 } } }));
+ expect(host.querySelector('[data-task-resources="1"]')).not.toBeNull();
+ expect(host.querySelector('[data-task-resources="1"] [data-task-resource="cpu"]')?.getAttribute('title'))
+ .toContain('全部后继');
+ expect(host.querySelector('[data-task-resources="2"]')).toBeNull();
+});
+
+it('旧快照未提供resources时不伪造资源指标', async () => {
+ const { host } = await open(payload({ running: [run()] }));
+ expect(host.querySelector('[data-task-resources]')).toBeNull();
+});
+
it('活动任务按服务端给出的动作暂停、继续和取消,并重新读取进度', async () => {
const posts: [string, unknown][] = [];
let current = run({ control: { state: 'running', actions: ['pause', 'cancel'] } });