import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react' import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom' import { History, Inbox, RefreshCw } from 'lucide-react' import { EmptyState, IconButton, PageHeader, StatusBadge, useTicker } from '../components/ui' import { UNSAVED_WORKFLOW_ID } from '../api/client' import { formatSpan } from '../lib/format' import { STATUS, type StatusCode } from '../lib/status' import { useCatalog, useOnReconnect } from '../store/catalog' import type { Approval, Run } from '../types' import type { Task } from '../typesApp' import { FilterBar, RunRows, StatusSegments, TaskRows, } from './runs/RunList' import { RunDetailView } from './runs/RunDetailView' import { RUNS_TABS, TAB_CODES, TAB_LABEL, ageMs, asTab, duplicateNames, isLiveRun, matchesCodes, parseQuery, runCode, stripStatusWords, type RunsTab, } from './runs/model' import { ORIGIN_TEXT, TASK_LOG_TEXT, UNSAVED_NAME, originLabel } from '../lib/terms' import { RunTabs, type TabItem } from './runs/parts' import { useApprovalQueue, useRunList, useStatusCounts, useTaskQueue } from './runs/useRunsData' import './runs/runs.css' /** * 记录:每次运行的完整事件流都落了库,所以这里能完整回放、排错、处理待办。 * * 地址就是状态:/runs?tab=approvals|running|failed|all,外加 status / class / wf / q * 几个筛选;/runs/:runId 打开某一条,筛选原样保留在查询串里。导航上的待审批 * 徽标指向 ?tab=approvals——这页必须能处理待办,否则刷新后卡在审批上的运行在 * 整个界面里没有任何入口可以推进。 */ export function RunsPage() { const { runId } = useParams() const navigate = useNavigate() const location = useLocation() const [params, setParams] = useSearchParams() const tab = asTab(params.get('tab')) const text = params.get('q') ?? '' const runClass = (['formal', 'exploratory'].includes(params.get('class') ?? '') ? params.get('class') : '') as '' | 'formal' | 'exploratory' const workflowId = params.get('wf') ?? '' const origin = params.get('origin') ?? '' const segment = (params.get('status') ?? '').split(',').filter((c): c is StatusCode => c in STATUS) const patchParams = useCallback((patch: Record) => { setParams((prev) => { const next = new URLSearchParams(prev) for (const [k, v] of Object.entries(patch)) { if (v == null || v === '') next.delete(k) else next.set(k, v) } return next }, { replace: true }) }, [setParams]) // 认不出的页签(链接过期、手输错)落回「全部」,并把地址一起纠正 const rawTab = params.get('tab') useEffect(() => { if (rawTab && rawTab !== tab) patchParams({ tab: tab === 'all' ? null : tab }) }, [rawTab, tab, patchParams]) // 搜索框:输入即时显示,停手 250ms 再写进地址、发请求 const [draft, setDraft] = useState(text) const typing = useRef(false) useEffect(() => { if (!typing.current) setDraft(text) }, [text]) useEffect(() => { if (draft === text) { typing.current = false; return } const t = setTimeout(() => { typing.current = false; patchParams({ q: draft || null }) }, 250) return () => clearTimeout(t) }, [draft, text, patchParams]) const parsed = useMemo(() => parseQuery(text), [text]) const approvals = useCatalog((s) => s.approvals) const catalogLoaded = useCatalog((s) => s.loaded) const workflows = useCatalog((s) => s.workflows) // epoch:手动刷新、断网恢复、删除之后,列表以外的几份(计数、待审批)一起重拉; // tick:轮询时只刷计数,待审批跟着 catalog 的轮询走,不另敲一遍 const [epoch, setEpoch] = useState(0) const [tick, setTick] = useState(0) const queue = useApprovalQueue(epoch) // 「待办」页签列的是待办(审批、补充输入、动作确认、核实);判「等待审批 / 已挂起」仍按待审批(queue) const tasks = useTaskQueue(epoch) // 判「等待审批 / 已挂起」用哪份待审批:页面自己那份上限高(500 条),没拿到 // 之前用 catalog 的;两份都没有时是 null,按等待审批算,不闪成「已挂起」 const known: Approval[] | null = queue.state === 'ok' ? queue.items : catalogLoaded ? approvals : null // 实际查询的状态:页签定死的范围和文字里的状态词取交集;「全部」里文字优先于分段 const tabCodes = tab === 'running' || tab === 'failed' ? TAB_CODES[tab] : null const codes: StatusCode[] = tabCodes ? (parsed.codes.length ? tabCodes.filter((c) => parsed.codes.includes(c)) : tabCodes) : (parsed.codes.length ? parsed.codes : segment) const impossible = !!tabCodes && parsed.codes.length > 0 && codes.length === 0 const filters = { codes, runClass, workflowId, q: parsed.q, origin } const list = useRunList(filters, tab !== 'approvals' && !impossible) // 计数两份:页签和分段上的跟着当前的类别、工作流、名称条件走;右侧总览说的 // 是全局——筛掉了不代表事情没了 const narrowed = !!(runClass || workflowId || parsed.q || origin) const countKey = epoch * 100_000 + tick const globalCounts = useStatusCounts({ runClass: '', workflowId: '', q: '' }, known, countKey) const narrowCounts = useStatusCounts({ runClass, workflowId, q: parsed.q, origin }, known, countKey, narrowed) const counts = narrowed ? narrowCounts : globalCounts const { reload: reloadList, patchRow, removeRow } = list const refreshAll = useCallback(() => { void reloadList() setEpoch((e) => e + 1) }, [reloadList]) // 断网恢复:列表、计数、待审批一起重拉,不停在「还没有运行记录」的假空态上 useOnReconnect(refreshAll) // 有在跑的:列表每 4 秒原地刷新(页面不可见时不刷);「运行中」页签一直刷, // 新发起的运行会自己出现 const hasLive = list.rows.some((r) => isLiveRun(r.status)) useEffect(() => { if (tab === 'approvals' || (tab !== 'running' && !hasLive)) return const t = setInterval(() => { if (document.hidden) return void reloadList({ silent: true }) setTick((n) => n + 1) }, 4000) return () => clearInterval(t) }, [tab, hasLive, reloadList]) // waiting / held 在后端都是 interrupted:查回来之后按审批列表再分一次 const codeSig = codes.join(',') const rows = useMemo( () => (impossible ? [] : list.rows.filter((r) => matchesCodes(r, codes, known))), [list.rows, codeSig, known, impossible], // codes 每次渲染都是新数组,按内容比 ) const shownList = impossible ? { ...list, rows: [], state: 'ok' as const, hasMore: false } : { ...list, rows } const dupNames = useMemo(() => duplicateNames([ ...workflows.map((w) => ({ id: w.id, name: w.name })), ...list.rows.map((r) => ({ id: r.workflow_id, name: r.workflow_name })), ]), [workflows, list.rows]) // 待办页签吃同样的名称条件。待办上只有工作流名,没有运行类别、工作流 id 和来源,那几项不筛它 const taskFilter = useCallback((t: Task) => !parsed.q || `${t.workflow_name ?? ''} ${t.title}`.toLowerCase().includes(parsed.q.toLowerCase()), [parsed.q]) const pendingOf = useCallback( (id: string) => known?.find((a) => a.run_id === id && a.status === 'pending'), [known], ) const codeOf = useCallback((r: Run) => runCode(r, known), [known]) const open = (id: string) => navigate({ pathname: `/runs/${id}`, search: location.search }) // 详情里那一条变了:原地换掉列表里的那一行;状态变了顺带刷新计数 const lastStatus = useRef(new Map()) const onRunChange = useCallback((run: Run) => { patchRow(run) const before = lastStatus.current.get(run.id) lastStatus.current.set(run.id, run.status) if (before && before !== run.status) setTick((n) => n + 1) }, [patchRow]) const onDeleted = useCallback((id: string) => { removeRow(id) setEpoch((e) => e + 1) navigate({ pathname: '/runs', search: location.search }, { replace: true }) }, [removeRow, navigate, location.search]) const now = useTicker(60_000) const queueItems = tasks.items.filter(taskFilter) const oldest = oldestAge(queueItems, now) const running = (counts.counts.running ?? 0) + (counts.counts.queued ?? 0) const failed = counts.counts.failed ?? 0 const plus = counts.saturated ? '+' : '' const allRunning = (globalCounts.counts.running ?? 0) + (globalCounts.counts.queued ?? 0) const allFailed = globalCounts.counts.failed ?? 0 const allPlus = globalCounts.saturated ? '+' : '' const allPending = tasks.items.length const allOldest = oldestAge(tasks.items, now) const tabs: TabItem[] = RUNS_TABS.map((key) => { if (key === 'approvals') { return { key, label: TAB_LABEL[key], count: queueItems.length, tone: 'alert', title: queueItems.length ? `${queueItems.length} 条待办${oldest != null ? `,最久已等待 ${formatSpan(oldest, { coarse: true })}` : ''}` : TASK_LOG_TEXT.emptyTitle, } } if (key === 'running') return { key, label: TAB_LABEL[key], count: running, countLabel: `${running}${plus}`, tone: 'live' } if (key === 'failed') return { key, label: TAB_LABEL[key], count: failed, countLabel: `${failed}${plus}`, tone: 'quiet' } return { key, label: TAB_LABEL[key] } }) const setTab = (k: RunsTab) => patchParams({ tab: k === 'all' ? null : k }) const setText = (v: string) => { typing.current = true; setDraft(v) } const pickSegment = (code: StatusCode | null) => { // 点了分段,文字里原来的状态词就不该再和它打架 const rest = stripStatusWords(draft) typing.current = false setDraft(rest) patchParams({ status: code, q: rest || null }) } const clearFilters = () => { typing.current = false setDraft('') patchParams({ q: null, status: null, class: null, wf: null, origin: null }) } const filterNote = describeFilters({ tab, parsed, segment, runClass, workflowId, workflows, origin }) return (
{/* 待审批的数不在页头里重复——紧下面的页签上就有 */} } title="记录" subtitle="每次运行的完整轨迹、待处理的待办和封存凭证" actions={} onClick={refreshAll} data-runs-refresh="" />} />
{/* 外壳已经有
,这里再套一个就是两个主区域地标 */}
{runId ? : }
) } /** 一批待办里等得最久的那条等了多久;空的是 null */ function oldestAge(items: { created_at?: string | null }[], now: number): number | null { return items.reduce((m, a) => { const age = ageMs(a.created_at, now) return age != null && (m == null || age > m) ? age : m }, null) } /** 列表里 ↑↓ 在行之间移动焦点,回车打开(行本身是按钮)。不在移动时就打开:每按一下就拉一次详情太吵 */ function moveInList(e: KeyboardEvent) { if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return const rows = [...e.currentTarget.querySelectorAll('[data-run-id][type=button], [data-task-id]')] const i = rows.indexOf(document.activeElement as HTMLElement) if (i < 0) return const next = rows[e.key === 'ArrowDown' ? Math.min(rows.length - 1, i + 1) : Math.max(0, i - 1)] if (!next || next === rows[i]) return e.preventDefault() next.focus() next.scrollIntoView({ block: 'nearest' }) } /** 空的「没有匹配」要说清是被哪些条件筛空的;没有任何条件时返回 null */ function describeFilters({ tab, parsed, segment, runClass, workflowId, workflows, origin }: { tab: RunsTab; parsed: ReturnType; segment: StatusCode[] runClass: string; workflowId: string; workflows: { id: string; name: string }[]; origin: string }): string | null { const parts: string[] = [] if (parsed.words.length) parts.push(`状态「${parsed.words.join('、')}」`) else if (tab === 'all' && segment.length) parts.push(`状态「${segment.map((c) => STATUS[c].short).join('、')}」`) if (parsed.q) parts.push(`名称含「${parsed.q}」`) if (runClass) parts.push(runClass === 'formal' ? '正式运行' : '探索运行') if (origin) parts.push(`来源「${origin === 'none' ? ORIGIN_TEXT.unknown : originLabel(origin)}」`) if (workflowId === UNSAVED_WORKFLOW_ID) parts.push(UNSAVED_NAME) else if (workflowId) parts.push(`工作流「${workflows.find((w) => w.id === workflowId)?.name ?? '已删除的工作流'}」`) if (!parts.length) return null return `筛选条件:${parts.join(' · ')}${tab !== 'all' ? `(在「${TAB_LABEL[tab]}」里)` : ''}` } /** * 没选中运行时的右侧:不是一句「选一条」,而是此刻要管的几件事——待审批、在跑的、 * 失败的,点了就去对应的页签。 */ function Overview({ pending, oldest, running, failed, plus, onTab }: { pending: number; oldest: number | null; running: number; failed: number; plus: string onTab: (t: RunsTab) => void }) { const tiles: { key: RunsTab; code: StatusCode; label: string; value: string; sub: string; alert: boolean }[] = [ { key: 'approvals', code: 'waiting', label: TASK_LOG_TEXT.tab, value: String(pending), sub: pending ? `最久已等待 ${formatSpan(oldest, { coarse: true })}` : '暂无待处理', alert: pending > 0, }, { key: 'running', code: 'running', label: '运行中', value: `${running}${running ? plus : ''}`, sub: running ? '可实时查看、随时停止' : '当前无运行中', alert: false }, { key: 'failed', code: 'failed', label: '失败', value: `${failed}${failed ? plus : ''}`, sub: failed ? '查看原因,可从断点继续运行' : '暂无失败', alert: false }, ] return (
{tiles.map((t, i) => ( ))}
} title="选择一条运行记录" body="在左侧选择一条记录,可查看完整的执行轨迹、总时长、执行时长、等待审批时长和封存凭证;失败的运行可从断点继续,待审批的可就地处理。" className="py-0" />
) }