+ {/* 窄时换行:不换行时这一行只有定时任务链接能缩,会被挤成 0 宽,其余各项被压成竖排 */}
+
{shortId(run.id)}
·
·
-
- {run.started_by || '未署名'} 发起
-
+ {/* 定时任务发起的:写成到那个定时任务的链接(键盘可达;记录页的「定时」标记只能鼠标点) */}
+ {run.schedule_id ? : (
+
+ {run.started_by || '未署名'} 发起
+
+ )}
·
{formatNumber(d.events.length)} 条事件
{workflowGone && · 工作流已删除}
diff --git a/frontend/src/pages/schedules/FireHistory.tsx b/frontend/src/pages/schedules/FireHistory.tsx
index 3e008910..aeafd8de 100644
--- a/frontend/src/pages/schedules/FireHistory.tsx
+++ b/frontend/src/pages/schedules/FireHistory.tsx
@@ -1,18 +1,20 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { Link } from 'react-router-dom'
-import { ChevronRight, History, RotateCw } from 'lucide-react'
+import { ChevronRight, GitCompareArrows, History, RotateCw } from 'lucide-react'
import { api } from '../../api/client'
import { EmptyState, ErrorState, Skeleton, Spinner, StatusPill, toast, useTicker } from '../../components/ui'
-import { formatDateTime, parseServerTime } from '../../lib/format'
+import { formatDateTime, parseServerTime, shortId } from '../../lib/format'
import { SCHEDULE_TEXT as T } from '../../lib/terms'
-import type { Schedule, ScheduleFire } from '../../types'
+import type { Schedule, ScheduleFire, ScheduleFireCompare } from '../../types'
+import { comparePath, type CompareVia } from '../runs/compare/entry'
import { FireKindChip, FireStatusChip, ZonedTime } from './parts'
const PAGE = 20
/**
* 触发历史:每次触发一行,新的在前,20 条一页、「加载更多」往后接。计划时间按定时任务的时区写;跳过、发起失败
- * 写原因;发起了的链到那次运行、写运行现在的状态;发出去的通知逐条写结果。refreshKey 变了(立即运行之后)从头重取
+ * 写原因;发起了的链到那次运行、写运行现在的状态;运行成功结束后服务端和同一任务上一次成功的运行比过的,另给
+ * 「与上一次对比」;发出去的通知逐条写结果。refreshKey 变了(立即运行之后)从头重取
*/
export function FireHistory({ schedule, refreshKey }: { schedule: Schedule; refreshKey: number }) {
const [items, setItems] = useState(null)
@@ -110,6 +112,7 @@ function FireRow({ fire: f, tz, now }: { fire: ScheduleFire; tz: string; now: nu
+ {f.run_id && f.compare && }
{f.run_id ? (
{f.run_status && }
@@ -137,3 +140,33 @@ function FireRow({ fire: f, tz, now }: { fire: ScheduleFire; tz: string; now: nu
)
}
+
+/**
+ * 「与上一次对比」:去对比页,本次是这次触发的运行、基准是服务端自动对比时取的同一任务上一次成功的运行。旁边写有几个
+ * 指标有变化(触屏没有悬停,键盘聚焦也不显示悬停),悬停写各类指标的个数(和通知里那一行同一个写法),读屏把它当
+ * 说明念。基准就是紧挨着的上一次时带上来历,对比页据此写「默认基准:同一定时任务的上一次运行」;不是(上一次失败了、
+ * 取消了)时不带,免得说错,悬停写明比的是哪一次
+ */
+function CompareLink({ runId, compare }: { runId: string; compare: ScheduleFireCompare }) {
+ const previous = compare.previous !== false
+ const via: CompareVia | undefined = previous ? { base: compare.base_run_id, reason: 'same_schedule' } : undefined
+ const count = T.compareCount(compare.summary)
+ return (
+
+
+ {T.compareLink}
+ {count && (
+ <>
+ ·
+ {count}
+ >
+ )}
+
+ )
+}
diff --git a/frontend/src/pages/schedules/WebhookFields.tsx b/frontend/src/pages/schedules/WebhookFields.tsx
index 16c8c2c8..2041d5c9 100644
--- a/frontend/src/pages/schedules/WebhookFields.tsx
+++ b/frontend/src/pages/schedules/WebhookFields.tsx
@@ -9,7 +9,7 @@ import type { ScheduleEvent, ScheduleWebhook, ScheduleWebhookTest } from '../../
import { SCHEDULE_EVENTS, WEBHOOK_FORMATS, isHttpUrl, webhookTestText, type FormField, type WebhookForm } from './model'
/**
- * Webhook 通知:格式、地址、签名密钥、订阅事件、发送测试消息,外加通知里运行链接用的服务访问地址。
+ * Webhook 通知:格式、地址、签名密钥、订阅事件、发送测试消息,外加通知里运行、对比页链接用的服务访问地址。
*
* 地址和密钥保存之后服务端不再返回明文:地址只显示主机和末 4 位(url_hint),可以替换或删除;密钥只说「已设置」,
* 可以替换或清除。没点替换时请求里不带它们,改别的字段不会把地址清掉。测试消息用的是已保存的设置,
@@ -195,7 +195,7 @@ function SecretField({ value: w, saved, onChange, error }: {
}
/**
- * 通知里运行链接用的服务访问地址:设置里 notify 一组的 public_base_url,所有定时任务共用。这里给出当前值和修改入口,
+ * 通知里运行、对比页链接用的服务访问地址:设置里 notify 一组的 public_base_url,所有定时任务共用。这里给出当前值和修改入口,
* 写的时候先重读一遍 notify 组、只换这一项,不把同组别的设置冲掉
*/
function LinkBase() {
diff --git a/frontend/src/pages/schedules/parts.tsx b/frontend/src/pages/schedules/parts.tsx
index bd0e14f0..1e0e8069 100644
--- a/frontend/src/pages/schedules/parts.tsx
+++ b/frontend/src/pages/schedules/parts.tsx
@@ -223,6 +223,11 @@ export const isUnsupported = (e: unknown) => e instanceof ApiError && e.status =
* 不认识的 id 再取一次列表(一分钟内最多一次)。取不到(老服务端、暂时连不上)不要紧,标记照样显示,只是不写名字
*/
const names = new Map()
+/**
+ * 已删除的定时任务:取回的列表里没有的(列表是全部定时任务,服务端不分页),或者刚在本页删掉的。运行详情页头据此不再
+ * 链过去。列表没取到时谁都不算删除:只是不知道
+ */
+const missing = new Set()
let fetchedAt = 0
let inflight: Promise | null = null
let namesVersion = 0
@@ -236,16 +241,30 @@ const emitNames = () => {
/** 记下读到的定时任务名字(gone 里的是刚删掉的) */
export function rememberScheduleNames(items: Pick[], gone: string[] = []) {
- for (const s of items) names.set(s.id, s.name)
- for (const id of gone) names.delete(id)
+ for (const s of items) {
+ names.set(s.id, s.name)
+ missing.delete(s.id)
+ }
+ for (const id of gone) {
+ names.delete(id)
+ missing.add(id)
+ }
emitNames()
}
function ensureNames(ids: string[]) {
- if (inflight || !ids.some((id) => !names.has(id)) || Date.now() - fetchedAt < NAMES_RETRY_MS) return
+ if (inflight || !ids.some((id) => !names.has(id) && !missing.has(id)) || Date.now() - fetchedAt < NAMES_RETRY_MS) return
inflight = api.schedules.list({ timeoutMs: 10_000 })
- .then((r) => { for (const s of r.items ?? []) names.set(s.id, s.name) })
- .catch(() => { /* 取不到就不写名字 */ })
+ .then((r) => {
+ const items = r.items ?? []
+ for (const s of items) {
+ names.set(s.id, s.name)
+ missing.delete(s.id)
+ }
+ const listed = new Set(items.map((s) => s.id))
+ for (const id of ids) if (!listed.has(id)) missing.add(id)
+ })
+ .catch(() => { /* 取不到就不写名字,也不算删除 */ })
.finally(() => {
inflight = null
fetchedAt = Date.now()
@@ -253,6 +272,9 @@ function ensureNames(ids: string[]) {
})
}
+/** 这个定时任务已删除(取回的列表里没有它、或者刚在本页删掉)。和 useScheduleNames 一起用:取回来后会重渲染 */
+export const scheduleGone = (id: string) => missing.has(id)
+
/** 这些定时任务的名字(id → 名字)。没记过的去取一次,取回来后重渲染 */
export function useScheduleNames(ids: (string | null | undefined)[]): ReadonlyMap {
useSyncExternalStore(
@@ -269,8 +291,8 @@ export function useScheduleNames(ids: (string | null | undefined)[]): ReadonlyMa
* 这里拦住冒泡,只去定时任务、不打开运行。
*
* 按钮里放不了可聚焦的链接(读屏会把按钮里的内容压平,Tab 也到不了),所以键盘到不了这个标记:读屏改念
- * 「由定时任务「X」发起」,至少在整行的名字里听到来源。键盘可达的入口要放到运行详情的页头,或者把整行改成
- * 「打开运行」按钮和这个链接并排,都不在本页的文件里,见交付说明
+ * 「由定时任务「X」发起」,至少在整行的名字里听到来源。键盘可达的入口在运行详情的页头(RunScheduleSource):
+ * 打开这次运行之后,Tab 就能到那条链接
*/
export function ScheduleTag({ scheduleId, name }: { scheduleId: string; name?: string | null }) {
const navigate = useNavigate()
@@ -291,3 +313,55 @@ export function ScheduleTag({ scheduleId, name }: { scheduleId: string; name?: s
)
}
+
+// -------------------------------------------------------------------------
+// 运行详情页头的来源
+// -------------------------------------------------------------------------
+
+/**
+ * 运行详情页头里「谁发起的」那一段,定时任务发起的运行用它:「由定时任务「X」发起」是真的链接,Tab 到得了、回车能
+ * 打开,去那个定时任务的设置和触发历史。记录页的「定时」标记在整行按钮里,只能用鼠标点,键盘的入口在这里。
+ *
+ * 到点发起的运行(以及没有署名的立即运行)记在「定时任务:X」名下:原来那句「定时任务:X 发起」整句换成这条链接,
+ * 不写两遍。有人署名点「立即运行」的,署名照写,后面接「来自定时任务「X」」。名字取定时任务现在的名字(改过名的写
+ * 新名字),取不到时用署名里记的那个,再没有就不写名字。
+ *
+ * 前面带和「定时」标记一样的日历图标:页头这一行都是灰字,不带记号看不出这一段能点。页头窄时这一行换行,链接至少留
+ * 几个字宽(以前这一行不换行,只有链接能缩,窄窗口里被挤成 0 宽,Tab 停在一个看不见的链接上),再长截断,全名在悬停里。
+ * 定时任务已经删除的写成纯文本(链过去只有「不存在」页),同一行的「工作流已删除」也是这样
+ */
+export function RunScheduleSource({ scheduleId, startedBy }: { scheduleId: string; startedBy?: string | null }) {
+ const names = useScheduleNames([scheduleId])
+ const recorded = startedBy?.startsWith(T.actorPrefix) ? startedBy.slice(T.actorPrefix.length).trim() : null
+ const auto = !startedBy || recorded != null
+ const name = names.get(scheduleId) || recorded || null
+ const body = (text: string) => (
+ <>
+
+ {text}
+ >
+ )
+ const source = scheduleGone(scheduleId) ? (
+
+ {body(auto ? T.runSourceGone(name) : T.runSourceManualGone(name))}
+
+ ) : (
+
+ {body(auto ? T.runSource(name) : T.runSourceManual(name))}
+
+ )
+ if (auto || !startedBy) return source
+ return (
+ <>
+ {T.runStarter(startedBy)}
+ ·
+ {source}
+ >
+ )
+}
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index cd09e0ba..999d08e5 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -3207,6 +3207,20 @@ export interface ScheduleFireNotice {
at: string
}
+/**
+ * 运行成功结束后和同一定时任务上一次成功的运行的自动对比:基准是哪一次、各类指标的个数(同对比接口的 summary)。
+ * 只有个数,具体的数在对比页上
+ */
+export interface ScheduleFireCompare {
+ base_run_id: string
+ summary: RunCompareSummary
+ /**
+ * 基准是不是紧挨着的上一次。上一次失败了、取消了时,基准是再往前成功的那一次,为 false:界面写明比的是哪一次。
+ * 老服务端不给,按 true 看
+ */
+ previous?: boolean
+}
+
/** 一次触发(触发历史的一行) */
export interface ScheduleFire {
id: string
@@ -3220,6 +3234,11 @@ export interface ScheduleFire {
/** 跳过、发起失败的原因(中文) */
reason: string | null
notified: ScheduleFireNotice[]
+ /**
+ * 和同一定时任务上一次成功的运行的对比。运行没有成功结束、没有可比的、还没算、比不了、任何一边又在执行(不在终态)
+ * 或重新封存过时为 null;老服务端不给
+ */
+ compare?: ScheduleFireCompare | null
created_at: string
}
diff --git a/scripts/check-schedules.mjs b/scripts/check-schedules.mjs
index b125f897..f5c5b0bc 100644
--- a/scripts/check-schedules.mjs
+++ b/scripts/check-schedules.mjs
@@ -3,7 +3,11 @@
// 守的是这些「看着没坏、其实不能用」的地方:预设生成的 cron 不对(选了每周一 09:00,交上去的是每天)、时区按本机写
// 而不是按定时任务的时区、预览不防抖、非法 cron 只弹一句不知道指哪一项、启用开关不带版本号(别人改过也照样覆盖)、
// 立即运行之后没有下文、触发历史只有一页、保存过的 Webhook 地址又被原样显示出来、改了别的字段却把地址清掉、
-// 记录页看不出哪些运行来自定时任务、390px 窄屏被表单撑出横向滚动。
+// 记录页看不出哪些运行来自定时任务、390px 窄屏被表单撑出横向滚动。运行成功结束后的自动对比:触发历史里「与上一次
+// 对比」(和运行详情「更多」菜单同一个叫法)链到对比页,旁边写有几个指标有变化,悬停只写各类指标的个数,基准不是
+// 紧挨着的上一次时写明是哪一次、不带「默认基准」的来历;运行详情页头的「由定时任务「X」发起」是键盘到得了的真链接
+// (记录页的「定时」标记在整行按钮里,只能鼠标点),带日历图标,窄窗口里(768、820、900 宽,探索运行多一个「提取为
+// 草稿」)不被挤没,定时任务删掉之后写成纯文本。
// 还有几处时序和口径:晚到的刷新把刚切换的开关盖回去、先开触发历史再开设置时带着旧版本撞假的 409、保存途中又改了
// 别的字段时替换过的地址明文留在框里、服务端会拒的组合(未发布 + 正式运行、必填没填、已发布版本里没有的字段)
// 照样放行、测试消息的结果把服务端的整句又套一层、错过已跳过的那条悬停另说一个原因(和本条记的原因对不上)。
@@ -263,6 +267,24 @@ await section('纯函数:服务端会拒的组合、保存回来怎么接、
check(`测试结果:服务端给整句、给补充说明都只说一遍(${tests.length} 种)`, !wrong.length, wrong.map(([r]) => t(r)).join(';'))
})
+await section('纯函数:触发历史对比的文案', async () => {
+ const { SCHEDULE_TEXT: T, RUN_COMPARE_TEXT: C } = await import(await load('/src/lib/terms.ts'))
+ check('「与上一次对比」和运行详情「更多」菜单同一个叫法', T.compareLink === C.menu && T.compareLink === '与上一次对比', T.compareLink)
+ const zero = { unchanged: 0, data_only: 0, caliber_and_data: 0, sql_changed: 0, params_only: 0, added: 0, removed: 0, incomparable: 0 }
+ const cases = [
+ ['有变化的几类合起来', { ...zero, data_only: 3, caliber_and_data: 1, params_only: 2, unchanged: 4 }, '6 个指标有变化'],
+ ['新增、移除也算变化', { ...zero, added: 1, removed: 2 }, '3 个指标有变化'],
+ ['没有变化、有无法比较的', { ...zero, incomparable: 2, unchanged: 3 }, '2 个指标无法比较'],
+ ['都未变', { ...zero, unchanged: 5 }, '指标都未变'],
+ ['两边都没有指标:不写', zero, null],
+ ]
+ const bad = cases.filter(([, sum, want]) => T.compareCount(sum) !== want)
+ check(`看得见的计数:${cases.length} 种情况`, !bad.length, bad.map(([n, sum]) => `${n}:${T.compareCount(sum)}`).join(';'))
+ check('悬停:基准不是紧挨着的上一次时写明是哪一次', T.compareTitle({ ...zero, data_only: 1 }, '#run-f1')
+ === '与上一次成功的运行(#run-f1)相比:只数据变 1 个、口径与数据都变 0 个、SQL 结构变 0 个'
+ && T.compareTitle(zero, '#run-f1') === '与上一次成功的运行(#run-f1)相比:两次运行都没有指标')
+})
+
// ---------------------------------------------------------------- 夹具:虚构的门店周报、库存日报
const NOW = Date.now()
@@ -375,6 +397,16 @@ const S2 = {
* 原因却有两种,各放一条、原因照服务端的原话写:f03 是停机一周多、在宽限内恢复时积压的那一次(最近一次就是补发的
* f02),f05 是超出补发宽限的。f06、f07 没有记原因(约定里 reason 可以是 null),看兜底的说明
*/
+/** 服务端自动对比给的计数(只有个数):f00 和同一任务的上一次(run-f02)比过 */
+const COMPARE_F00 = { base_run_id: 'run-f02', previous: true, summary: { unchanged: 4, data_only: 3, caliber_and_data: 1,
+ sql_changed: 0, params_only: 2, added: 0, removed: 0, incomparable: 0 } }
+const COMPARE_F00_TITLE = '与上一次相比:只数据变 3 个、口径与数据都变 1 个、SQL 结构变 0 个、只参数变 2 个、未变 4 个'
+const NO_METRICS = { base_run_id: 'run-f09', previous: true, summary: { unchanged: 0, data_only: 0, caliber_and_data: 0,
+ sql_changed: 0, params_only: 0, added: 0, removed: 0, incomparable: 0 } }
+/** f10 的上一次(f11)失败了:基准是再往前成功的 f12,不是紧挨着的上一次 */
+const COMPARE_F10 = { base_run_id: 'run-f12', previous: false, summary: { unchanged: 1, data_only: 1, caliber_and_data: 0,
+ sql_changed: 0, params_only: 0, added: 0, removed: 0, incomparable: 0 } }
+
function makeFires() {
const out = []
const local = (at) => {
@@ -385,14 +417,17 @@ function makeFires() {
for (let i = 0; i < 25; i++) {
const at = iso(nextMonday9(-(i + 1)))
let f = fire(`f${String(i).padStart(2, '0')}`, { fire_at: at, created_at: at })
- if (i === 0) f = { ...f, kind: 'manual', notified: [{ event: 'finished', status: 'ok', at }, { event: 'failed', status: 'failed', at }] }
+ if (i === 0) f = { ...f, kind: 'manual', compare: COMPARE_F00, notified: [{ event: 'finished', status: 'ok', at }, { event: 'failed', status: 'failed', at }] }
if (i === 1) f = { ...f, status: 'skipped_overlap', run_id: null, run_status: null, reason: '上一次运行(#9f8e7d)尚未结束' }
- if (i === 2) f = { ...f, kind: 'misfire', run_status: 'failed' }
+ if (i === 2) f = { ...f, kind: 'misfire', run_status: 'failed', compare: null }
if (i === 3) f = { ...f, ...missed, reason: `服务未运行,错过了 ${local(at)} 的触发;积压的触发不补,只发起最近一次` }
if (i === 4) f = { ...f, status: 'failed_to_start', run_id: null, run_status: null, reason: '工作流「门店周报」还没有发布:正式运行需要已发布的版本' }
if (i === 5) f = { ...f, ...missed, reason: `服务未运行,错过了 ${local(at)} 的触发,超出补发宽限(1 小时),没有发起` }
if (i === 6) f = { ...f, ...missed, reason: null }
if (i === 7) f = { ...f, status: 'failed_to_start', run_id: null, run_status: null, reason: null }
+ if (i === 8) f = { ...f, compare: NO_METRICS }
+ if (i === 10) f = { ...f, compare: COMPARE_F10 }
+ if (i === 11) f = { ...f, run_status: 'failed', compare: null }
out.push(f)
}
return out
@@ -401,12 +436,30 @@ function makeFires() {
const RUNS = [
{ id: 'run-sched-1', workflow_id: 'wf-weekly', workflow_name: '门店周报', status: 'succeeded', input: { date: '2026-10-04' },
output: { 周报: '上周销售额 1,234 万元' }, error: null, usage: { duration_ms: 4200 }, run_class: 'formal', version: 3,
+ started_by: '定时任务:门店周报(旧名)',
schedule_id: 's-weekly', created_at: iso(NOW - 2 * H), started_at: iso(NOW - 2 * H), finished_at: iso(NOW - 2 * H + 4200) },
{ id: 'run-manual-1', workflow_id: 'wf-weekly', workflow_name: '门店周报', status: 'succeeded', input: { date: '2026-10-03' },
output: { 周报: '手动补一份' }, error: null, usage: { duration_ms: 3900 }, run_class: 'exploratory', version: null,
schedule_id: null, created_at: iso(NOW - 3 * H), started_at: iso(NOW - 3 * H), finished_at: iso(NOW - 3 * H + 3900) },
]
+/** 有人署名点了「立即运行」:署名照写,页头另接到定时任务的链接 */
+const RUN_MANUAL_FIRE = { ...RUNS[0], id: 'run-sched-2', started_by: '检查员甲', created_at: iso(NOW - H), started_at: iso(NOW - H),
+ finished_at: iso(NOW - H + 4200) }
+/** 探索运行成功了,页头多一个「提取为草稿」,这一行更挤:到点发起的、署名点了立即运行的各一次 */
+const RUN_EXPLORE = { ...RUNS[0], id: 'run-sched-3', run_class: 'exploratory', version: null, started_by: '定时任务:门店周报 · 每周' }
+const RUN_EXPLORE_MANUAL = { ...RUN_EXPLORE, id: 'run-sched-4', started_by: '检查员甲' }
+/** 运行详情要的图和事件:一个节点、开始到结束两条,够页头和时间线画出来 */
+const RUN_GRAPH = { nodes: [{ id: 'out', type: 'output', position: { x: 0, y: 0 }, data: { label: '成果', config: {} } }], edges: [] }
+function runEvents(run) {
+ const t0 = Date.parse(run.started_at) / 1000
+ return [
+ { seq: 1, type: 'run.started', node_id: null, ts: t0, data: { nodes: 1 } },
+ { seq: 2, type: 'run.finished', node_id: null, ts: t0 + 4.2,
+ data: { output: run.output, usage: {}, timing: { wall_ms: 4200, active_ms: 4200, wait_ms: 0 } } },
+ ]
+}
+
function freshState(patch = {}) {
return {
schedules: [structuredClone(S1), structuredClone(S2)],
@@ -538,7 +591,13 @@ async function reply(state, method, path, url, body) {
if (state.runs && method === 'GET' && path.startsWith('/runs/')) {
const run = state.runs.find((r) => path === `/runs/${r.id}`)
if (run) return { json: run }
+ const m = path.match(/^\/runs\/([^/]+)\/(events|graph|artifacts)$/)
+ const of = m && state.runs.find((r) => r.id === m[1])
+ if (of && m[2] === 'events') return { json: runEvents(of) }
+ if (of && m[2] === 'graph') return { json: { graph: RUN_GRAPH, workflow_id: of.workflow_id, version: of.version } }
+ if (of) return { json: [] }
}
+ if (state.runs && method === 'GET' && path === '/approvals' && url.searchParams.get('run_id')) return { json: [] }
return null
}
@@ -621,6 +680,18 @@ const saveDone = (page) => until(async () => {
/** 等预览算完、说的是这个频率 */
const previewSays = (page, words) => until(async () => (await page.locator('[data-schedule-preview][data-status="ok"]').count()) === 1
&& (await page.locator('[data-schedule-preview]').innerText()).includes(words))
+/**
+ * 只按 Tab 键把焦点移到 sel 上:从页面开头往后按,最多按 max 次。按到了返回按了几次,按不到返回 0。键盘可达就是
+ * 这个意思——鼠标能点、程序能 focus() 的不算
+ */
+const tabTo = async (page, sel, max = 160) => {
+ await page.evaluate(() => document.activeElement?.blur?.())
+ for (let i = 1; i <= max; i++) {
+ await page.keyboard.press('Tab')
+ if (await page.evaluate((s) => !!document.activeElement?.matches?.(s), sel)) return i
+ }
+ return 0
+}
/** 元素整个在视口的横向范围里 */
const inViewX = (page, sel) => page.evaluate((s) => {
const el = document.querySelector(s)
@@ -628,6 +699,40 @@ const inViewX = (page, sel) => page.evaluate((s) => {
const b = el.getBoundingClientRect()
return b.left >= 0 && b.right <= innerWidth + 0.5
}, sel)
+/**
+ * 元素的字和它实际落在上面的底色的对比度(WCAG 算法),{ratio, fg, bg},找不到元素为 null。底色顺着祖先往上找,
+ * 半透明的一层层叠上去,直到不透明的那层(都透明就按白底)。只比「字色和某个容器的底色不相等」不够:页头本身是
+ * 透明的,那样比永远成立
+ */
+const readable = (page, sel) => page.evaluate((s) => {
+ const el = document.querySelector(s)
+ if (!el) return null
+ const parse = (c) => {
+ const m = c.match(/color\(srgb ([\d.]+) ([\d.]+) ([\d.]+)(?: \/ ([\d.]+))?\)/)
+ if (m) return [m[1] * 255, m[2] * 255, m[3] * 255, m[4] == null ? 1 : Number(m[4])]
+ const n = c.match(/rgba?\(([\d.]+),\s*([\d.]+),\s*([\d.]+)(?:,\s*([\d.]+))?\)/)
+ return n ? [Number(n[1]), Number(n[2]), Number(n[3]), n[4] == null ? 1 : Number(n[4])] : null
+ }
+ const over = (top, under) => top.slice(0, 3).map((v, i) => v * top[3] + under[i] * (1 - top[3]))
+ const layers = []
+ for (let n = el; n; n = n.parentElement) {
+ const c = parse(getComputedStyle(n).backgroundColor)
+ if (c && c[3] > 0) layers.push(c)
+ if (c && c[3] >= 1) break
+ }
+ let bg = [255, 255, 255]
+ for (const layer of layers.reverse()) bg = over(layer, bg)
+ const color = parse(getComputedStyle(el).color)
+ if (!color) return null
+ const fg = over(color, bg)
+ const lum = (rgb) => {
+ const [r, g, b] = rgb.map((v) => { const x = v / 255; return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4 })
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b
+ }
+ const [hi, lo] = [lum(fg), lum(bg)].sort((a, b) => b - a)
+ return { ratio: Math.round(((hi + 0.05) / (lo + 0.05)) * 100) / 100, fg: getComputedStyle(el).color,
+ bg: `rgb(${bg.map(Math.round).join(', ')})` }
+}, sel)
// ---------------------------------------------------------------- 列表
@@ -1089,8 +1194,10 @@ await section('详情:Webhook 与运行链接地址', async () => {
&& !('secret' in (p2?.webhook ?? {})), JSON.stringify(p2))
check('……保存后又只显示 url_hint', await until(async () => (await text(page, '[data-webhook-url-hint]').catch(() => '')).includes('…cd34'))
&& await page.locator('[data-webhook-url]').count() === 0)
- // 运行链接地址:读写设置的 notify 组
- check('写出运行链接地址还没设置', (await text(page, '[data-link-base]')).includes('未设置'))
+ // 运行链接地址:读写设置的 notify 组。对比页链接也按它拼,说明里一并说到
+ const unset = await text(page, '[data-link-base]')
+ check('写出运行链接地址还没设置,没有它时运行和对比页链接都不附', unset.includes('未设置') && unset.includes('运行和对比页链接'),
+ oneLine([unset]))
await page.locator('[data-link-base-edit]').click()
await page.locator('[data-link-base-input]').fill('ftp://bad')
check('地址不对时不让存', await page.locator('[data-link-base-save]').isDisabled())
@@ -1335,6 +1442,220 @@ await section('详情:触发历史分页', async () => {
&& await gone.page.locator('[data-schedule-missing] a[href="/schedules"]').count() === 1)
})
+await section('详情:触发历史里的「与上一次对比」', async () => {
+ const { page, sent, errors } = await open('/schedules/s-weekly?tab=history')
+ await page.locator('[data-fire-id]').first().waitFor()
+ const row = (id) => page.locator(`[data-fire-id="${id}"]`)
+ const link = row('f00').locator('[data-fire-compare]')
+ const label = await link.locator('[data-fire-compare-label]').innerText().catch(() => '没有链接')
+ check('有对比的那次:给「与上一次对比」(和运行详情「更多」菜单同一个叫法)', (await link.count()) === 1
+ && label.trim() === '与上一次对比', label)
+ check('……链到对比页,本次是这次的运行、基准是服务端比过的那一次',
+ await link.getAttribute('href') === '/runs/compare?target=run-f00&base=run-f02', (await link.getAttribute('href')) ?? '')
+ const count = (await link.locator('[data-fire-compare-count]').innerText().catch(() => '')).trim()
+ check('……旁边看得见有几个指标有变化(触屏、键盘看不到悬停)', count === '6 个指标有变化', count)
+ const title = (await link.getAttribute('title')) ?? ''
+ check('……悬停写各类指标的个数:三类总写,其余有才写,没有数值', title === COMPARE_F00_TITLE, title)
+ const f08 = row('f08').locator('[data-fire-compare]')
+ check('两边都没有指标:悬停不写一串 0 个,旁边也不写计数', ((await f08.getAttribute('title')) ?? '')
+ === '与上一次相比:两次运行都没有指标' && await f08.locator('[data-fire-compare-count]').count() === 0)
+ const f10 = row('f10').locator('[data-fire-compare]')
+ const t10 = (await f10.getAttribute('title').catch(() => '')) ?? ''
+ check('上一次失败了、基准是再往前成功的那次:悬停写明是哪一次', t10.startsWith('与上一次成功的运行(#run-f1)相比:只数据变 1 个'), t10)
+ const linked = await page.locator('[data-fire-compare]').evaluateAll((els) => els.map((e) => e.closest('[data-fire-id]')?.getAttribute('data-fire-id')))
+ check('没有对比的(compare 为 null、老服务端不给、没有运行)不给链接', JSON.stringify(linked) === '["f00","f08","f10"]', JSON.stringify(linked))
+ check('运行链接照旧在', await row('f00').locator('a[href="/runs/run-f00"]').count() === 1)
+ const presses = await tabTo(page, '[data-fire-id="f00"] [data-fire-compare]')
+ check('键盘:Tab 到得了「与上一次对比」', presses > 0, `按了 ${presses} 次`)
+ await shot(page, 'history-compare-focus-dark')
+ await page.keyboard.press('Enter')
+ const url = await until(() => {
+ const u = new URL(page.url())
+ return u.pathname === '/runs/compare' ? u : null
+ })
+ check('……回车打开对比页,带着本次和基准', !!url && url.searchParams.get('target') === 'run-f00'
+ && url.searchParams.get('base') === 'run-f02', page.url())
+ // 来历跟着这一次跳转走(路由的 state),对比页据此写「默认基准:同一定时任务的上一次运行」
+ const via = await page.evaluate(() => history.state?.usr ?? null)
+ check('……紧挨着的上一次:带上「同一定时任务」的来历', via?.reason === 'same_schedule' && via?.base === 'run-f02', JSON.stringify(via))
+
+ const second = await open('/schedules/s-weekly?tab=history')
+ await second.page.locator('[data-fire-id="f10"] [data-fire-compare]').click()
+ await until(() => new URL(second.page.url()).pathname === '/runs/compare')
+ const via10 = await second.page.evaluate(() => history.state?.usr ?? null)
+ check('……基准不是紧挨着的上一次:不带来历,对比页不说「上一次」', new URL(second.page.url()).searchParams.get('base') === 'run-f12'
+ && via10 == null, JSON.stringify(via10))
+ const real = [...writes(sent, /./), ...writes(second.sent, /./)].filter((x) => x.key !== 'POST /schedules/preview')
+ check('只读:没有写请求', real.length === 0, real.map((x) => x.key).join('、'))
+ check('没有页面报错', ![...errors, ...second.errors].length, [...errors, ...second.errors].join(' | '))
+})
+
+// ---------------------------------------------------------------- 运行详情
+
+/**
+ * 运行详情页头元信息那一行:定时任务的链接(或删除后的纯文本)可见的宽度够不够写下图标加「由定时任务」五个字(fits),
+ * 「N 条事件」是不是还在一行里(eventsFlat,以前被挤成一字一行),页头有没有横向溢出,链接在不在视口里,署名在不在
+ */
+const headRow = (page) => page.evaluate(() => {
+ const head = document.querySelector('[data-run-detail] header')
+ const link = head?.querySelector('[data-run-schedule-link], [data-run-schedule-gone]')
+ if (!head || !link) return null
+ const font = parseFloat(getComputedStyle(link).fontSize)
+ const icon = link.querySelector('svg')?.getBoundingClientRect().width ?? 0
+ const l = link.getBoundingClientRect()
+ const events = [...head.querySelectorAll('span')].find((el) => /^[\d,]+ 条事件$/.test(el.textContent.trim()))
+ const eh = events?.getBoundingClientRect().height ?? 0
+ return { width: Math.round(l.width), need: Math.round(icon + 4 + font * 5), fits: l.width >= icon + 4 + font * 5 - 0.5,
+ eventsFlat: !!events && eh > 0 && eh < font * 2.2, scroll: head.scrollWidth - head.clientWidth,
+ inView: l.left >= 0 && l.right <= innerWidth + 0.5 && l.width > 0, starter: head.innerText.includes('检查员甲 发起') }
+})
+
+await section('运行详情:页头的定时任务链接', async () => {
+ const writesSeenExtra = []
+ const errorsExtra = []
+ const state = freshState({ runs: [...RUNS, RUN_MANUAL_FIRE] })
+ const { page, sent, errors } = await open('/runs/run-sched-1', { state })
+ await page.locator('[data-run-detail="run-sched-1"]').waitFor({ timeout: 10000 })
+ const head = page.locator('[data-run-detail] header').first()
+ const link = head.locator('[data-run-schedule-link]')
+ // 署名里记的是旧名字:取到定时任务列表之后写现在的名字
+ const said = await until(async () => {
+ const t = (await link.innerText().catch(() => '')).trim()
+ return t === '由定时任务「门店周报 · 每周」发起' ? t : null
+ })
+ check('页头写「由定时任务「X」发起」,X 是定时任务现在的名字', !!said, (await link.innerText().catch(() => '没有链接')).trim())
+ check('……是到那个定时任务的真链接', (await link.evaluate((el) => el.tagName)) === 'A'
+ && await link.getAttribute('href') === '/schedules/s-weekly', (await link.getAttribute('href')) ?? '')
+ const headText = await head.innerText()
+ check('……不再另写「定时任务:X 发起」', !headText.includes('定时任务:') && !headText.includes('旧名'), oneLine([headText]).slice(0, 160))
+ check('……悬停写全名和点开去哪', ((await link.getAttribute('title')) ?? '').includes('门店周报 · 每周'))
+ check('……前面带和「定时」标记一样的日历图标,平时看得出能点', await link.locator('svg').count() === 1)
+ const presses = await tabTo(page, '[data-run-detail] header [data-run-schedule-link]')
+ check('键盘:Tab 到得了页头的定时任务链接', presses > 0, `按了 ${presses} 次`)
+ const ring = await page.evaluate(() => getComputedStyle(document.activeElement).boxShadow)
+ check('……聚焦时有焦点环', !!ring && ring !== 'none', ring)
+ const darkTone = await readable(page, '[data-run-detail] header [data-run-schedule-link]')
+ check('深色:页头的定时任务链接对比度 ≥ 4.5', !!darkTone && darkTone.ratio >= 4.5, JSON.stringify(darkTone))
+ await shot(page, 'run-detail-schedule-link-dark')
+ await page.keyboard.press('Enter')
+ check('……回车去那个定时任务', await until(() => new URL(page.url()).pathname === '/schedules/s-weekly'), page.url())
+ await page.locator('[data-schedule-form], [data-schedules-page] header').first().waitFor()
+
+ const manual = await open('/runs/run-sched-2', { state: freshState({ runs: [...RUNS, RUN_MANUAL_FIRE] }) })
+ await manual.page.locator('[data-run-detail="run-sched-2"]').waitFor({ timeout: 10000 })
+ const mHead = manual.page.locator('[data-run-detail] header').first()
+ const mLink = mHead.locator('[data-run-schedule-link]')
+ await until(async () => (await mLink.innerText().catch(() => '')).includes('门店周报 · 每周'))
+ const mText = oneLine([await mHead.innerText()])
+ check('有人署名点了立即运行:署名照写,后面接「来自定时任务「X」」的链接', mText.includes('检查员甲 发起')
+ && (await mLink.innerText()).trim() === '来自定时任务「门店周报 · 每周」' && await mLink.getAttribute('href') === '/schedules/s-weekly',
+ mText.slice(0, 160))
+
+ await shot(manual.page, 'run-detail-manual-fire-dark')
+ const light = await open('/runs/run-sched-1', { state: freshState({ runs: [...RUNS, RUN_MANUAL_FIRE] }), theme: 'light' })
+ await light.page.locator('[data-run-detail="run-sched-1"] header [data-run-schedule-link]').waitFor()
+ const lightTheme = await light.page.evaluate(() => document.documentElement.dataset.theme)
+ const lightTone = await readable(light.page, '[data-run-detail] header [data-run-schedule-link]')
+ check('浅色:页头的定时任务链接对比度 ≥ 4.5', lightTheme === 'light' && !!lightTone && lightTone.ratio >= 4.5,
+ `${lightTheme} ${JSON.stringify(lightTone)}`)
+ await shot(light.page, 'run-detail-schedule-link-light')
+ const plain = await open('/runs/run-manual-1', { state: freshState({ runs: [...RUNS, RUN_MANUAL_FIRE] }) })
+ await plain.page.locator('[data-run-detail="run-manual-1"]').waitFor({ timeout: 10000 })
+ check('手动发起的运行:页头没有定时任务链接', await plain.page.locator('[data-run-detail] header [data-run-schedule-link]').count() === 0)
+
+ // 名字很长、详情区不宽时链接截断,不把页头撑宽(全名在悬停里)
+ const longName = freshState({ runs: [...RUNS, RUN_MANUAL_FIRE] })
+ longName.schedules = longName.schedules.map((x) => (x.id === 's-weekly' ? { ...x, name: '华东区全部门店按品类与渠道拆分的周度销售与退款复盘' } : x))
+ const narrow = await open('/runs/run-sched-1', { state: longName, width: 900 })
+ await narrow.page.locator('[data-run-detail="run-sched-1"]').waitFor({ timeout: 10000 })
+ const nLink = narrow.page.locator('[data-run-detail] header [data-run-schedule-link]')
+ await until(async () => (await nLink.innerText().catch(() => '')).includes('复盘'))
+ const fit = await narrow.page.evaluate(() => {
+ const head = document.querySelector('[data-run-detail] header')
+ const link = head?.querySelector('[data-run-schedule-link]')
+ const label = link?.querySelector('span')
+ if (!head || !link || !label) return null
+ const h = head.getBoundingClientRect()
+ const l = link.getBoundingClientRect()
+ return { headRight: Math.round(h.right), linkRight: Math.round(l.right), scroll: head.scrollWidth - head.clientWidth,
+ clipped: label.scrollWidth > label.clientWidth }
+ })
+ check('长名字:链接截断,不超出页头、页头不横向溢出', !!fit && fit.linkRight <= fit.headRight && fit.scroll <= 1 && fit.clipped,
+ JSON.stringify(fit))
+ // 署名的立即运行(署名加链接,这一行最挤)配长名字:链接照样截断,署名不被挤掉
+ const crowdedState = freshState({ runs: [...RUNS, RUN_MANUAL_FIRE] })
+ crowdedState.schedules = longName.schedules
+ const crowded = await open('/runs/run-sched-2', { state: crowdedState, width: 900 })
+ await crowded.page.locator('[data-run-detail="run-sched-2"]').waitFor({ timeout: 10000 })
+ const cLink = crowded.page.locator('[data-run-detail] header [data-run-schedule-link]')
+ await until(async () => (await cLink.innerText().catch(() => '')).includes('复盘'))
+ const crowd = await headRow(crowded.page)
+ check('……署名的立即运行配长名字:署名照写,链接截断、看得到,页头不横向溢出', !!crowd && crowd.starter
+ && crowd.fits && crowd.scroll <= 1 && crowd.inView, JSON.stringify(crowd))
+
+ // 分屏常见的窄窗口:探索运行的页头多一个「提取为草稿」,这一行最挤。以前这一行不换行、只有链接能缩,820 宽时链接
+ // 只剩「由…」,768 宽时 0 宽,Tab 停在一个看不见的链接上,「2 条事件」被压成竖排
+ const tight = []
+ for (const [width, run, extract] of [[820, RUN_EXPLORE, true], [820, RUN_EXPLORE_MANUAL, true],
+ [768, RUN_EXPLORE, true], [768, RUN_EXPLORE_MANUAL, true], [768, RUN_MANUAL_FIRE, false]]) {
+ const one = await open(`/runs/${run.id}`, { state: freshState({ runs: [...RUNS, RUN_MANUAL_FIRE, RUN_EXPLORE, RUN_EXPLORE_MANUAL] }), width })
+ await one.page.locator(`[data-run-detail="${run.id}"] header [data-run-schedule-link]`).waitFor({ timeout: 10000 })
+ await until(async () => (await one.page.locator('[data-run-detail] header [data-run-schedule-link]').innerText()).includes('门店周报 · 每周'))
+ const got = await headRow(one.page)
+ const hasExtract = await one.page.locator('[data-run-detail] header [data-action="extract"]').count() === 1
+ const manual = run.started_by === '检查员甲'
+ const ok = !!got && got.fits && got.eventsFlat && got.scroll <= 1 && got.inView && hasExtract === extract
+ && (!manual || got.starter)
+ tight.push(ok)
+ check(`${width} 宽、${run.run_class === 'exploratory' ? '探索' : '正式'}运行(${manual ? '署名点了立即运行' : '到点发起'}):链接至少写得下「由定时任务」,「条事件」不被压成竖排`,
+ ok, JSON.stringify({ ...got, hasExtract }))
+ const presses = await tabTo(one.page, '[data-run-detail] header [data-run-schedule-link]')
+ if (width === 768 && manual && extract) {
+ check('……最挤的那种 Tab 到链接时看得见(有宽度、在视口里)', presses > 0 && !!got && got.width > 0 && got.inView, `按了 ${presses} 次`)
+ await shot(one.page, 'run-detail-schedule-link-768')
+ }
+ writesSeenExtra.push(...writes(one.sent, /./))
+ errorsExtra.push(...one.errors)
+ }
+
+ // 定时任务已经删了:取回的列表里没有它,不再链过去(只会落到「不存在」页),写成纯文本,和「工作流已删除」一样
+ const goneState = freshState({ runs: [...RUNS, RUN_MANUAL_FIRE] })
+ goneState.schedules = goneState.schedules.filter((x) => x.id !== 's-weekly')
+ const gone = await open('/runs/run-sched-1', { state: goneState })
+ await gone.page.locator('[data-run-detail="run-sched-1"]').waitFor({ timeout: 10000 })
+ const goneEl = gone.page.locator('[data-run-detail] header [data-run-schedule-gone]')
+ await goneEl.waitFor({ timeout: 6000 }).catch(() => {})
+ check('定时任务已删除:写「由定时任务「X」发起(已删除)」,不是链接', (await goneEl.count()) === 1
+ && (await goneEl.innerText()).trim() === '由定时任务「门店周报(旧名)」发起(已删除)'
+ && await gone.page.locator('[data-run-detail] header [data-run-schedule-link]').count() === 0
+ && (await goneEl.evaluate((el) => el.tagName)) !== 'A', (await goneEl.innerText().catch(() => '没有')).trim())
+ check('……悬停说已删除、运行记录仍然保留', ((await goneEl.getAttribute('title')) ?? '').includes('已删除'))
+ const goneManual = await open('/runs/run-sched-2', { state: goneState })
+ await goneManual.page.locator('[data-run-detail="run-sched-2"]').waitFor({ timeout: 10000 })
+ const gmEl = goneManual.page.locator('[data-run-detail] header [data-run-schedule-gone]')
+ await gmEl.waitFor({ timeout: 6000 }).catch(() => {})
+ check('……署名点了立即运行的:署名照写,后面是「来自已删除的定时任务」', oneLine([await goneManual.page.locator('[data-run-detail] header').first().innerText()]).includes('检查员甲 发起')
+ && (await gmEl.innerText().catch(() => '')).trim() === '来自已删除的定时任务', (await gmEl.innerText().catch(() => '没有')).trim())
+ // 列表取不到(老服务端、暂时连不上)不算删除:照样是链接,用署名里记的名字
+ const downState = freshState({ runs: [...RUNS, RUN_MANUAL_FIRE] })
+ downState.override = (method, path) => (method === 'GET' && path === '/schedules' ? { status: 503, json: { detail: '暂时不可用' } } : null)
+ const down = await open('/runs/run-sched-1', { state: downState })
+ const downLink = down.page.locator('[data-run-detail="run-sched-1"] header [data-run-schedule-link]')
+ await downLink.waitFor({ timeout: 10000 })
+ await sleep(300)
+ check('……定时任务列表取不到时不算删除,照样是链接', await down.page.locator('[data-run-detail] header [data-run-schedule-gone]').count() === 0
+ && (await downLink.innerText()).trim() === '由定时任务「门店周报(旧名)」发起')
+ writesSeenExtra.push(...writes(gone.sent, /./), ...writes(goneManual.sent, /./), ...writes(down.sent, /./))
+ errorsExtra.push(...gone.errors, ...goneManual.errors, ...down.errors)
+ // 回车打开的定时任务页会请求预览(POST,但只读),不算写
+ const writesSeen = [...writes(sent, /./), ...writes(manual.sent, /./), ...writes(light.sent, /./), ...writes(plain.sent, /./),
+ ...writes(narrow.sent, /./), ...writes(crowded.sent, /./), ...writesSeenExtra]
+ .filter((x) => x.key !== 'POST /schedules/preview')
+ check('只读:没有写请求', writesSeen.length === 0, writesSeen.map((x) => x.key).join('、'))
+ const all = [...errors, ...manual.errors, ...light.errors, ...plain.errors, ...narrow.errors, ...crowded.errors, ...errorsExtra]
+ check('没有页面报错', !all.length, all.join(' | '))
+})
+
// ---------------------------------------------------------------- 记录页
await section('记录页:定时标记', async () => {
@@ -1416,6 +1737,12 @@ await section('窄屏 390px 与浅色', async () => {
const hist = await open('/schedules/s-weekly?tab=history', { ...narrow, theme })
await hist.page.locator('[data-fire-id]').first().waitFor()
check(`${theme}:触发历史不横向溢出`, await overflow(hist.page) <= 1, `${await overflow(hist.page)}px`)
+ check(`${theme}:「与上一次对比」和旁边的计数在屏幕里`, await inViewX(hist.page, '[data-fire-id="f00"] [data-fire-compare]')
+ && await inViewX(hist.page, '[data-fire-id="f00"] [data-fire-compare-count]'))
+ const cmp = await readable(hist.page, '[data-fire-id="f00"] [data-fire-compare]')
+ check(`${theme}:「与上一次对比」对比度 ≥ 4.5`, !!cmp && cmp.ratio >= 4.5, JSON.stringify(cmp))
+ const cnt = await readable(hist.page, '[data-fire-id="f00"] [data-fire-compare-count]')
+ check(`${theme}:旁边的计数对比度 ≥ 4.5`, !!cnt && cnt.ratio >= 4.5, JSON.stringify(cnt))
check(`${theme}:页头的开关、立即运行、删除在屏幕里`, await inViewX(hist.page, 'header [data-schedule-run]')
&& await inViewX(hist.page, 'header [data-schedule-toggle]') && await inViewX(hist.page, 'header [data-schedule-delete]'))
await shot(hist.page, `history-390-${theme}`)