feat: 对齐后端能力并补齐形态提示词与生产诊断

This commit is contained in:
GouJ committed 2026-09-02 18:21:20 +08:00
1 parent 7d8074f90e
commit f71d2bf0a4
30 files changed
+1707 -66

No files matched your search

+14 -3
View File
@@ -1,13 +1,15 @@
<script setup lang="ts">
import { computed } from 'vue'
import { NScrollbar, NEmpty, NTimeline, NTimelineItem } from 'naive-ui'
import { computed, ref } from 'vue'
import { NButton, NScrollbar, NEmpty, NTimeline, NTimelineItem } from 'naive-ui'
import { Clock3 } from '@lucide/vue'
import { formatDate, nodeLabel } from '../../lib/format'
import { workflowCheckpoints } from './selectors'
import type { Checkpoint } from './types'
import WorkflowDiagnosticsDialog from './WorkflowDiagnosticsDialog.vue'
/** 时间线只说明 checkpoint 已保存,不把每条记录误标为工作流成功。 */
const props = defineProps<{ checkpoints: Checkpoint[]; workflow: string }>()
const props = defineProps<{ checkpoints: Checkpoint[]; workflow: string; projectId?: string }>()
const diagnosticsOpen = ref(false)
const history = computed(() => workflowCheckpoints(props.checkpoints, props.workflow).slice(-18).toReversed())
</script>
@@ -16,6 +18,9 @@ const history = computed(() => workflowCheckpoints(props.checkpoints, props.work
<NScrollbar class="panel-scroll" content-class="history-content">
<h3 class="mb-1 flex items-center gap-2 text-sm font-semibold"><Clock3 :size="15" />执行记录</h3>
<p class="mb-6 text-xs leading-5 text-muted">最近 18 个 checkpoint · 自动刷新</p>
<NButton v-if="projectId" text size="small" class="mb-4" @click="diagnosticsOpen = true"
>查看完整运行诊断</NButton
>
<NEmpty v-if="!history.length" size="small" description="工作流尚未保存执行记录。" />
<NTimeline v-else>
<NTimelineItem
@@ -41,5 +46,11 @@ const history = computed(() => workflowCheckpoints(props.checkpoints, props.work
记录在节点或批次结束后更新,长时间无新记录不一定意味着任务失败。
</p>
</NScrollbar>
<WorkflowDiagnosticsDialog
v-if="projectId"
v-model:open="diagnosticsOpen"
:project-id="projectId"
:checkpoints="checkpoints"
/>
</aside>
</template>
@@ -0,0 +1,163 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { NAlert, NButton, NCollapse, NCollapseItem, NInput, NSelect, NTab, NTabs } from 'naive-ui'
import { Download, RefreshCw, Search } from '@lucide/vue'
import { AppDialog, EmptyState } from '../../components/ui'
import { usePolling } from '../../composables/usePolling'
import { downloadText, formatDate, nodeLabel } from '../../lib/format'
import { loadWorkflowDiagnostics } from './diagnostics'
import type { Checkpoint } from './types'
/** 完整诊断按需读取,关闭或切项目取消旧查询;不把保存记录误标为执行成功。 */
const props = defineProps<{ projectId: string; checkpoints: Checkpoint[] }>()
const open = defineModel<boolean>('open', { default: false })
const key = computed(() => (open.value ? props.projectId : ''))
const query = usePolling(key, (id, signal) => (id ? loadWorkflowDiagnostics(id, signal) : Promise.resolve(null)), 12000)
const tab = ref('timeline')
const workflow = ref('all')
const search = ref('')
const checkpointMap = computed(() => new Map(props.checkpoints.map(item => [item.checkpointId, item])))
const options = computed(() => [
{ label: '全部工作流', value: 'all' },
...[...new Set(props.checkpoints.map(item => item.workflowName))].map(value => ({ label: value, value }))
])
const groups = computed(() =>
(query.data.value?.groups ?? [])
.map(group => ({
...group,
nodes: group.nodes.filter(
node =>
(workflow.value === 'all' ||
checkpointMap.value.get(node.checkpointId)?.workflowName === workflow.value) &&
`${node.nodeName} ${nodeLabel(node.nodeName)} ${node.checkpointId}`
.toLowerCase()
.includes(search.value.trim().toLowerCase())
)
}))
.filter(group => group.nodes.length)
)
const nodes = computed(() => groups.value.flatMap(group => group.nodes).toSorted((a, b) => a.index - b.index))
watch(
() => props.projectId,
() => {
workflow.value = 'all'
search.value = ''
tab.value = 'timeline'
}
)
/** 只根据 checkpoint 中明确的执行错误显示失败,未知结果仍标记为已保存。 */
function recordLabel(id: string) {
return checkpointMap.value.get(id)?.state.workflowExecution?.status === 'failed' ? '包含失败记录' : '记录已保存'
}
/** 导出原始指标和完整分组,不被视图中的筛选裁剪。 */
function exportReport() {
if (query.data.value)
downloadText(
`project-${props.projectId}-diagnostics.json`,
JSON.stringify({ projectId: props.projectId, ...query.data.value }, null, 2),
'application/json'
)
}
</script>
<template>
<AppDialog
v-model:open="open"
title="工作流运行诊断"
description="展示全项目已保存的 checkpoint 指标与完整时间线,不启动或恢复任务。"
wide
>
<NAlert type="info" :show-icon="false" class="mt-4 text-xs"
>后端指标按保存记录累计;耗时之和不等于实际墙钟耗时,“completed”也不代表图片或视频成功。生产任务状态请以资产页面为准。</NAlert
>
<NAlert v-if="query.error.value" role="alert" type="error" :show-icon="false" class="mt-3"
>{{ query.error.value }},当前保留上次数据。</NAlert
>
<NAlert
v-for="error in query.data.value?.errors"
:key="error"
role="alert"
type="error"
:show-icon="false"
class="mt-3"
>{{ error }}</NAlert
>
<div class="mt-4 flex flex-wrap items-center justify-between gap-3">
<div class="flex flex-wrap items-center gap-4 text-sm">
<template v-if="query.data.value?.metrics">
<span>全项目记录 {{ query.data.value.metrics.nodeCount }}</span>
<span>累计节点耗时 {{ query.data.value.metrics.totalDurationText }}</span>
<span>最近记录重试数 {{ query.data.value.metrics.retryCount }}</span>
</template>
<span v-else class="text-muted">{{ query.loading.value ? '读取诊断中…' : '运行指标暂不可用' }}</span>
</div>
<div class="flex items-center gap-2">
<NButton :disabled="!query.data.value" @click="exportReport"
><template #icon><Download :size="14" /></template>导出诊断</NButton
><NButton
class="icon-button"
:loading="query.loading.value"
aria-label="刷新运行诊断"
@click="query.refresh"
><template #icon><RefreshCw :size="16" /></template
></NButton>
</div>
</div>
<div class="diagnostics-filters mt-5">
<NInput
v-model:value="search"
clearable
placeholder="搜索节点或 checkpoint"
:input-props="{ 'aria-label': '搜索运行记录' }"
><template #prefix><Search :size="14" /></template
></NInput>
<NSelect v-model:value="workflow" :options="options" aria-label="筛选工作流" />
<span class="text-xs text-muted">{{ nodes.length }} 条记录</span>
</div>
<NTabs v-model:value="tab" type="line" class="mt-3"
><NTab name="timeline">完整时间线</NTab><NTab name="grouped">按阶段分组</NTab></NTabs
>
<div v-if="tab === 'timeline'" class="diagnostics-records mt-4">
<article v-for="node in nodes" :key="node.checkpointId" class="surface-inset p-4">
<div class="flex flex-wrap items-center justify-between gap-3">
<h3 class="text-sm font-medium">{{ node.index }} · {{ nodeLabel(node.nodeName) }}</h3>
<span
class="text-xs"
:class="recordLabel(node.checkpointId) === '包含失败记录' ? 'text-danger' : 'text-muted'"
>{{ recordLabel(node.checkpointId) }}</span
>
</div>
<p class="mt-2 text-xs text-muted">
{{ checkpointMap.get(node.checkpointId)?.workflowName || '未标注工作流' }} · {{ node.phase }} ·
{{ node.durationText }} · {{ formatDate(node.createdAt) }}
</p>
<p class="mt-2 break-all font-mono text-[11px] text-muted">{{ node.checkpointId }}</p>
</article>
</div>
<NCollapse v-else class="mt-4"
><NCollapseItem
v-for="group in groups"
:key="group.phase"
:name="group.phase"
:title="`${group.phase} · ${group.nodes.length} 条`"
>
<div class="diagnostics-records">
<article v-for="node in group.nodes" :key="node.checkpointId" class="surface-inset p-4">
<p class="text-sm">{{ nodeLabel(node.nodeName) }} · {{ node.durationText }}</p>
<p class="mt-2 text-xs text-muted">
{{ checkpointMap.get(node.checkpointId)?.workflowName || '未标注工作流' }} ·
{{ recordLabel(node.checkpointId) }}
</p>
<p class="mt-2 break-all font-mono text-[11px] text-muted">{{ node.checkpointId }}</p>
</article>
</div>
</NCollapseItem></NCollapse
>
<EmptyState
v-if="!query.loading.value && !nodes.length"
title="暂无匹配的运行记录"
description="可清空筛选后重试;尚未保存 checkpoint 的任务不会出现在时间线中。"
/>
</AppDialog>
</template>
+166
View File
@@ -0,0 +1,166 @@
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import WorkflowDiagnosticsDialog from './WorkflowDiagnosticsDialog.vue'
import { loadWorkflowDiagnostics, type WorkflowTimelineGroup } from './diagnostics'
import type { Checkpoint } from './types'
let wrapper: VueWrapper | undefined
afterEach(() => {
wrapper?.unmount()
wrapper = undefined
document.body.innerHTML = ''
vi.unstubAllGlobals()
})
/** 后端将 checkpoint 固定标为 completed,测试确保界面不把它当执行成功。 */
const groups: WorkflowTimelineGroup[] = [
{
phase: '其它',
nodeCount: 22,
durationMs: 22000,
durationText: '22s',
nodes: Array.from({ length: 22 }, (_, index) => ({
index: index + 1,
checkpointId: `checkpoint-${index}`,
nodeName: `node-${index}`,
phase: '其它',
status: 'completed',
durationMs: 1000,
durationText: '1s',
retryCount: 0,
createdAt: '2026-09-01T00:00:00Z'
}))
}
]
const metrics = {
projectId: 'diagnostics-test',
nodeCount: 22,
totalDurationText: '22s',
retryCount: 1,
successRate: 100,
failedNodeCount: 0
}
describe('运行观测入口', () => {
it('关闭时不请求,打开只读两个接口,完整展示超过 18 条记录且不伪造成功率', async () => {
const fetcher = vi
.fn<typeof fetch>()
.mockImplementation(
async url => new Response(JSON.stringify({ data: String(url).endsWith('/metrics') ? metrics : groups }))
)
vi.stubGlobal('fetch', fetcher)
const checkpoints: Checkpoint[] = [
{
checkpointId: 'checkpoint-0',
workflowName: 'breakdown',
createdAt: '2026-09-01T00:00:00Z',
state: {
workflowExecution: {
status: 'failed',
executionId: 'execution-1',
startedAt: '2026-09-01T00:00:00Z'
}
}
}
]
wrapper = mount(WorkflowDiagnosticsDialog, {
attachTo: document.body,
props: { projectId: 'diagnostics-test', open: false, checkpoints }
})
await flushPromises()
expect(fetcher).not.toHaveBeenCalled()
await wrapper.setProps({ open: true })
await flushPromises()
expect(fetcher).toHaveBeenCalledTimes(2)
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
expect(document.querySelectorAll('.diagnostics-records article')).toHaveLength(22)
expect(document.body.textContent).toContain('包含失败记录')
expect(document.body.textContent).not.toContain('100%')
const input = document.querySelector<HTMLInputElement>('[aria-label="搜索运行记录"]')!
input.value = 'checkpoint-21'
input.dispatchEvent(new Event('input', { bubbles: true }))
await flushPromises()
expect(document.querySelectorAll('.diagnostics-records article')).toHaveLength(1)
})
it('一个观测接口失败仍显示另一项,不启动恢复或生产', async () => {
const fetcher = vi
.fn<typeof fetch>()
.mockImplementation(async url =>
String(url).endsWith('/metrics')
? new Response(JSON.stringify({ error: '指标不可用' }), { status: 500 })
: new Response(JSON.stringify({ data: groups }))
)
vi.stubGlobal('fetch', fetcher)
const result = await loadWorkflowDiagnostics('project/1')
expect(result.metrics).toBeNull()
expect(result.groups?.[0]?.nodes).toHaveLength(22)
expect(result.errors[0]).toContain('指标')
expect(fetcher.mock.calls[0]?.[0]).toBe('/api/projects/project%2F1/metrics')
expect(fetcher.mock.calls[1]?.[0]).toBe('/api/projects/project%2F1/timeline/grouped')
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
})
it('指标项目不匹配时拒绝展示', async () => {
vi.stubGlobal(
'fetch',
vi
.fn<typeof fetch>()
.mockImplementation(
async url => new Response(JSON.stringify({ data: String(url).endsWith('/metrics') ? metrics : [] }))
)
)
const result = await loadWorkflowDiagnostics('other-project')
expect(result.metrics).toBeNull()
expect(result.errors.join()).toContain('不匹配的项目')
})
it('切项目会取消旧查询,晚到响应不会写进新项目', async () => {
const pending: ((response: Response) => void)[] = []
const fetcher = vi.fn<typeof fetch>().mockImplementation(url =>
String(url).includes('/old/')
? new Promise(resolve => pending.push(resolve))
: Promise.resolve(
new Response(
JSON.stringify({
data: String(url).endsWith('/metrics')
? { ...metrics, projectId: 'new', nodeCount: 0 }
: []
})
)
)
)
vi.stubGlobal('fetch', fetcher)
wrapper = mount(WorkflowDiagnosticsDialog, {
attachTo: document.body,
props: { projectId: 'old', open: true, checkpoints: [] }
})
await flushPromises()
const signal = fetcher.mock.calls[0]?.[1]?.signal
await wrapper.setProps({ projectId: 'new' })
await flushPromises()
expect(signal?.aborted).toBe(true)
pending[0]!(new Response(JSON.stringify({ data: { ...metrics, projectId: 'old' } })))
pending[1]!(new Response(JSON.stringify({ data: groups })))
await flushPromises()
expect(document.querySelectorAll('.diagnostics-records article')).toHaveLength(0)
expect(document.body.textContent).toContain('全项目记录 0')
await wrapper.setProps({ open: false })
await flushPromises()
expect(fetcher).toHaveBeenCalledTimes(4)
})
it('关闭弹窗时取消仍未返回的查询', async () => {
const finishes: ((response: Response) => void)[] = []
const fetcher = vi.fn<typeof fetch>().mockImplementation(() => new Promise(resolve => finishes.push(resolve)))
vi.stubGlobal('fetch', fetcher)
wrapper = mount(WorkflowDiagnosticsDialog, {
attachTo: document.body,
props: { projectId: 'diagnostics-test', open: true, checkpoints: [] }
})
await flushPromises()
await wrapper.setProps({ open: false })
await flushPromises()
expect(fetcher.mock.calls.every(([, init]) => init?.signal?.aborted)).toBe(true)
finishes[0]!(new Response(JSON.stringify({ data: metrics })))
finishes[1]!(new Response(JSON.stringify({ data: groups })))
await flushPromises()
expect(fetcher).toHaveBeenCalledTimes(2)
})
})
+70
View File
@@ -0,0 +1,70 @@
import { request, errorMessage } from '../../lib/http'
/** 后端指标按已保存 checkpoint 统计,不代表当前运行或失败任务数量。 */
export interface WorkflowMetrics {
projectId: string
nodeCount: number
totalDurationMs: number
totalDurationText: string
retryCount: number
/** 原始服务会把所有 checkpoint 视为完成,因此仅在 JSON 中保留这些字段。 */
completedNodeCount: number
failedNodeCount: number
runningNodeCount: number
pendingNodeCount: number
successRate: number
reviewPassed: boolean
projectStatus?: string
nodes: unknown[]
}
/** 单条时间线记录;status 是保存状态,不能用作模型结果判断。 */
export interface WorkflowTimelineNode {
index: number
checkpointId: string
nodeName: string
phase: string
status: string
durationMs: number
durationText: string
retryCount: number
reviewPassed?: boolean
projectStatus?: string
createdAt: string
}
/** 后端按节点阶段分组,阶段不是独立的工作流执行批次。 */
export interface WorkflowTimelineGroup {
phase: string
nodeCount: number
durationMs: number
durationText: string
nodes: WorkflowTimelineNode[]
}
/** 两项观测查询分别报错,单个接口失败不隐藏另一项成功结果。 */
export interface WorkflowDiagnostics {
metrics: WorkflowMetrics | null
groups: WorkflowTimelineGroup[] | null
errors: string[]
}
/** 仅读取已存在的观测接口,不调用 POST /resume(它只返回恢复信息)。 */
export async function loadWorkflowDiagnostics(projectId: string, signal?: AbortSignal): Promise<WorkflowDiagnostics> {
const path = `/projects/${encodeURIComponent(projectId)}`
const [metrics, groups] = await Promise.allSettled([
request<WorkflowMetrics>(`${path}/metrics`, { signal }).then(value => {
if (value.projectId !== projectId) throw new Error('运行指标返回了不匹配的项目。')
return value
}),
request<WorkflowTimelineGroup[]>(`${path}/timeline/grouped`, { signal })
])
return {
metrics: metrics.status === 'fulfilled' ? metrics.value : null,
groups: groups.status === 'fulfilled' ? groups.value : null,
errors: [
metrics.status === 'rejected' ? `指标:${errorMessage(metrics.reason)}` : '',
groups.status === 'rejected' ? `时间线:${errorMessage(groups.reason)}` : ''
].filter(Boolean)
}
}
+2
View File
@@ -132,6 +132,7 @@ async function mountSubjectImages() {
afterEach(() => {
getProductionSession(fixture.id).receipt = null
getProductionSession(fixture.id).pipelineReceipt = null
getIdentitySession(fixture.id).receipt = null
wrapper?.unmount()
wrapper = undefined
@@ -139,6 +140,7 @@ afterEach(() => {
vi.unstubAllGlobals()
Object.assign(getStoryboardSession(fixture.id), { receipt: null, prompts: {} })
getImageSession(fixture.id).receipt = null
getImageSession(fixture.id).promptReceipt = null
Object.assign(getOperation(fixture.id), { pending: false, label: '', error: '', notice: '' })
})