feat: 实现剧本创作与拆解前端工作台

This commit is contained in:
GouJ committed 2026-08-27 19:33:51 +08:00
1 parent edc003443f
commit 2ee6f049f6
56 files changed
+7597 -2

No files matched your search

+58
View File
@@ -0,0 +1,58 @@
<script setup lang="ts">
import { ref } from 'vue'
import { DialogTrigger } from 'reka-ui'
import { AppDialog } from '../../components/ui'
/** 耗费模型额度或覆盖结果的动作必须经过明确确认。 */
const props = defineProps<{
label: string
description: string
disabled?: boolean
acknowledgement?: boolean
primary?: boolean
}>()
const emit = defineEmits<{ confirm: [] }>()
const open = ref(false)
const acknowledged = ref(false)
/** 发出事件后关闭弹窗,操作状态由项目级锁负责。 */
function confirm() {
if (props.disabled || (props.acknowledgement && !acknowledged.value)) return
emit('confirm')
open.value = false
acknowledged.value = false
}
</script>
<template>
<AppDialog v-model:open="open" :title="label" :description="description">
<template #trigger
><DialogTrigger
class="button"
:class="primary ? 'button-primary' : 'button-secondary'"
:disabled="disabled"
>{{ label }}</DialogTrigger
></template
>
<p class="mt-5 text-sm leading-6 text-muted">
此操作会提交到真实后端,可能调用模型并产生费用。请勿在其他页面或终端同时启动相同工作流。
</p>
<label v-if="acknowledgement" class="mt-5 flex items-start gap-3 text-sm leading-6"
><input
v-model="acknowledged"
class="mt-1 accent-accent"
type="checkbox"
/>我已确认后台任务停止,当前没有同项目的生成或拆解任务在运行。</label
>
<div class="dialog-footer mt-6">
<button class="button button-secondary" @click="open = false">取消</button
><button
class="button button-primary"
:disabled="disabled || (acknowledgement && !acknowledged)"
@click="confirm"
>
确认{{ label }}
</button>
</div>
</AppDialog>
</template>
+36
View File
@@ -0,0 +1,36 @@
<script setup lang="ts">
import { computed } from 'vue'
import { Clock3 } from '@lucide/vue'
import { formatDate, nodeLabel } from '../../lib/format'
import { workflowCheckpoints } from './selectors'
import type { Checkpoint } from './types'
/** 时间线只说明 checkpoint 已保存,不把每条记录误标为工作流成功。 */
const props = defineProps<{ checkpoints: Checkpoint[]; workflow: string }>()
const history = computed(() => workflowCheckpoints(props.checkpoints, props.workflow).slice(-18).toReversed())
</script>
<template>
<aside class="history-panel">
<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>
<p v-if="!history.length" class="text-xs leading-6 text-muted">工作流尚未保存执行记录。</p>
<ol v-else class="timeline">
<li v-for="(item, index) in history" :key="item.checkpointId" :class="{ 'timeline-latest': index === 0 }">
<p class="text-xs font-medium">{{ nodeLabel(item.metadata?.nodeName) }}</p>
<p class="mt-1 text-[11px] text-muted">
{{ formatDate(item.createdAt)
}}<span v-if="item.metadata?.nodeDurationMs">
· {{ (item.metadata.nodeDurationMs / 1000).toFixed(1) }}s</span
>
</p>
<span v-if="item.state.workflowExecution?.status === 'failed'" class="mt-1 block text-xs text-danger"
>运行失败</span
>
</li>
</ol>
<p class="mt-5 border-t border-line pt-4 text-[11px] leading-5 text-muted">
记录在节点或批次结束后更新,长时间无新记录不一定意味着任务失败。
</p>
</aside>
</template>
+4
View File
@@ -0,0 +1,4 @@
/** 跨 graph 的观测与操作接口。 */
export { getOperation, runOperation } from './operations'
export { workflowCheckpoints, breakdownSnapshot, recoveryOptions } from './selectors'
export type { Checkpoint } from './types'
+20
View File
@@ -0,0 +1,20 @@
import { describe, expect, it, vi } from 'vitest'
import { getOperation, runOperation } from './operations'
describe('项目级长请求互斥', () => {
it('同一项目不同时执行两个 graph,错误不伪装成功', async () => {
let fail!: (reason: Error) => void
const action = vi.fn<() => Promise<unknown>>(
() =>
new Promise((_resolve, reject) => {
fail = reject
})
)
const first = runOperation('operation-test', '拆解', action)
expect(await runOperation('operation-test', '改写', action)).toBe(false)
expect(action).toHaveBeenCalledTimes(1)
fail(new Error('连接中断'))
expect(await first).toBe(false)
expect(getOperation('operation-test')).toMatchObject({ pending: false, error: '连接中断', notice: '' })
})
})
+35
View File
@@ -0,0 +1,35 @@
import { reactive } from 'vue'
import { errorMessage } from '../../lib/http'
/** 当前浏览器会话中的操作状态;切换路由不会丢失长请求。 */
export interface Operation {
pending: boolean
label: string
error: string
notice: string
}
/** 按项目而非 graph 上锁,防止改写剧本与拆解同时提交。 */
const operations = reactive<Record<string, Operation>>({})
/** 取得项目操作状态,不向浏览器持久化虚假的后台运行状态。 */
export function getOperation(projectId: string): Operation {
return (operations[projectId] ??= { pending: false, label: '', error: '', notice: '' })
}
/** 只提交一次;断网不自动重试,后台是否已执行由刷新后的 checkpoint 确认。 */
export async function runOperation(projectId: string, label: string, action: () => Promise<unknown>) {
const operation = getOperation(projectId)
if (operation.pending) return false
Object.assign(operation, { pending: true, label, error: '', notice: '' })
try {
await action()
operation.notice = '请求已返回,正在重新读取后端状态;最终结果以下方记录为准。'
return true
} catch (error) {
operation.error = errorMessage(error)
return false
} finally {
operation.pending = false
}
}
+142
View File
@@ -0,0 +1,142 @@
import { computed, ref } from 'vue'
import { createMemoryHistory, createRouter } from 'vue-router'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import CreateProjectDialog from '../projects/components/CreateProjectDialog.vue'
import BreakdownPage from '../breakdown/BreakdownPage.vue'
import CreateDramaPage from '../create-drama/CreateDramaPage.vue'
import ProjectsPage from '../projects/ProjectsPage.vue'
import { projectContextKey, type useProjectData } from '../projects/context'
import type { ProjectDetail } from '../projects/types'
import type { Checkpoint } from './types'
/** 模拟 API 响应仅用于测试,不会打包进生产页面。 */
const fixture: ProjectDetail = {
id: 'page-test-project',
title: '雨夜来信',
topic: '一封信改变了两个人的命运',
style: '都市悬疑',
status: 'completed',
createdAt: '2026-08-27T00:00:00Z',
updatedAt: '2026-08-27T00:00:00Z',
episodes: [{ episode: 1, title: '来信', content: '<script>不要执行模型内容</script>\n第一场:旧书店。' }],
characters: [{ id: 'character', name: '林知夏' }],
world: { era: '当代' },
reviews: [],
tasks: []
}
let wrapper: VueWrapper | undefined
/** 使用真实上下文形状,不绕过页面内的异步操作与按钮守卫。 */
function context(): ReturnType<typeof useProjectData> {
const data = ref({ project: fixture, checkpoints: [] as Checkpoint[] })
return {
data,
project: computed(() => data.value.project),
checkpoints: computed(() => data.value.checkpoints),
loading: ref(false),
error: ref(''),
updatedAt: ref(''),
refresh: vi.fn<() => Promise<void>>().mockResolvedValue()
}
}
/** 找到挂载到 body 的 Reka 弹窗按钮。 */
function button(label: string): HTMLButtonElement {
const element = [...document.querySelectorAll('button')].find(item => item.textContent?.trim() === label)
if (!element) throw new Error('找不到按钮:' + label)
return element
}
afterEach(() => {
wrapper?.unmount()
wrapper = undefined
document.body.innerHTML = ''
vi.unstubAllGlobals()
})
describe('工作台页面交互', () => {
it('项目筛选无结果时可清除条件并返回真实列表', async () => {
vi.stubGlobal(
'fetch',
vi.fn<typeof fetch>().mockImplementation(async () => new Response(JSON.stringify({ data: [fixture] })))
)
const router = createRouter({
history: createMemoryHistory(),
routes: [{ path: '/', component: ProjectsPage }]
})
await router.push('/')
wrapper = mount(ProjectsPage, { attachTo: document.body, global: { plugins: [router] } })
await flushPromises()
expect(wrapper.text()).toContain('雨夜来信')
await wrapper.get('input[aria-label="搜索项目"]').setValue('不存在的关键词')
expect(wrapper.text()).toContain('没有匹配的剧本')
button('清除筛选').click()
await flushPromises()
expect(wrapper.findAll('tbody tr')).toHaveLength(1)
})
it('新建弹窗提交真实参数并返回 202 的项目 ID', async () => {
const fetcher = vi
.fn<typeof fetch>()
.mockResolvedValue(new Response('{"projectId":"created","status":"generating"}', { status: 202 }))
vi.stubGlobal('fetch', fetcher)
wrapper = mount(CreateProjectDialog, { attachTo: document.body })
button('新建剧本').click()
await flushPromises()
const topic = document.querySelector<HTMLTextAreaElement>('#topic')!
topic.value = ' 雨夜来信 '
topic.dispatchEvent(new Event('input', { bubbles: true }))
const count = document.querySelector<HTMLInputElement>('#episode-count')!
count.value = '6'
count.dispatchEvent(new Event('input', { bubbles: true }))
document.querySelector('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))
await flushPromises()
expect(wrapper.emitted('created')).toEqual([['created']])
expect(JSON.parse(fetcher.mock.calls[0]![1]!.body as string)).toEqual({
topic: '雨夜来信',
style: '爽文反转',
episodeCount: 6
})
})
it('修改每组集数会废弃预览,重新预览并确认后才能启动', async () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async url => {
if (String(url).includes('breakdown-preview'))
return new Response(
'{"data":{"episodeCount":1,"groupCount":1,"estimatedTaskCount":3,"groups":[],"tasks":[],"modules":["character","scene","prop"],"groupSize":2}}'
)
return new Response('{"data":{"workflowExecution":{"status":"completed"}}}')
})
vi.stubGlobal('fetch', fetcher)
const provided = context()
wrapper = mount(BreakdownPage, {
attachTo: document.body,
global: { provide: { [projectContextKey as symbol]: provided } }
})
button('预览分组').click()
await flushPromises()
expect(button('开始拆解').disabled).toBe(false)
await wrapper.get('#group-size').setValue('2')
expect(document.body.textContent).not.toContain('开始拆解')
button('预览分组').click()
await flushPromises()
button('开始拆解').click()
await flushPromises()
button('确认开始拆解').click()
await flushPromises()
const post = fetcher.mock.calls.find(call => call[1]?.method === 'POST')
expect(post?.[0]).toBe('/api/projects/page-test-project/breakdown/start')
expect(JSON.parse(post![1]!.body as string)).toEqual({ groupSize: 2, modules: ['character', 'scene', 'prop'] })
expect(provided.refresh).toHaveBeenCalledOnce()
})
it('剧本文本按纯文本显示,不执行模型输出的 HTML', () => {
wrapper = mount(CreateDramaPage, {
attachTo: document.body,
global: { provide: { [projectContextKey as symbol]: context() }, stubs: { RouterLink: true } }
})
expect(wrapper.find('.script-body').text()).toContain('<script>不要执行模型内容</script>')
expect(wrapper.find('.script-body script').exists()).toBe(false)
})
})
+71
View File
@@ -0,0 +1,71 @@
import { describe, expect, it } from 'vitest'
import { breakdownSnapshot, recoveryOptions, workflowCheckpoints } from './selectors'
import type { Checkpoint } from './types'
import type { BreakdownState } from '../breakdown/types'
/** 只构造测试所需的真实 checkpoint 字段,避免页面依赖虚构 DTO。 */
function checkpoint(index: number, state: BreakdownState, workflowName = 'breakdown'): Checkpoint {
return { checkpointId: String(index), workflowName, createdAt: new Date(index * 1000).toISOString(), state }
}
describe('Checkpoint 选择与恢复', () => {
it('按 graph 隔离并保持输入不可变', () => {
const records = [checkpoint(2, {}), checkpoint(1, {}, 'create-drama')]
expect(workflowCheckpoints(records, 'breakdown').map(item => item.checkpointId)).toEqual(['2'])
expect(records[0]?.checkpointId).toBe('2')
})
it('只有错误的最新 checkpoint 仍能展示上一份成果,同时保留最新失败状态', () => {
const result = breakdownSnapshot([
checkpoint(1, {
breakdownResult: { subjectCandidates: [] },
runConfig: { groupSize: 3, modules: ['character'], episodeGroups: [] }
}),
checkpoint(2, {
workflowExecution: {
executionId: 'e',
status: 'failed',
startedAt: '',
errorMessage: '模型未返回 JSON'
}
})
])
expect(result?.runConfig?.groupSize).toBe(3)
expect(result?.workflowExecution?.status).toBe('failed')
})
it('新阶段不能继承上一轮 completed 状态', () => {
const result = breakdownSnapshot([
checkpoint(1, {
workflowExecution: { executionId: 'e', status: 'completed', startedAt: '' },
breakdownResult: {}
}),
checkpoint(2, { runConfig: { groupSize: 2, modules: ['scene'], episodeGroups: [] } })
])
expect(result?.workflowExecution).toBeUndefined()
expect(result?.runConfig?.groupSize).toBe(2)
})
it('恢复窗口和后端一致,过旧的失败任务不启用重试', () => {
const records = Array.from({ length: 11 }, (_, index) =>
checkpoint(
index,
index === 0
? {
tasks: [
{
taskId: 't',
module: 'prop',
status: 'failed',
attempt: 1,
group: { groupId: 'g', groupNo: 1, startEpisodeNo: 1, endEpisodeNo: 1, episodes: [] }
}
]
}
: {}
)
)
expect(recoveryOptions(records).retry).toBe(false)
expect(recoveryOptions(records.slice(0, 10)).retry).toBe(true)
})
})
+45
View File
@@ -0,0 +1,45 @@
import type { BreakdownState } from '../breakdown/types'
import type { Checkpoint } from './types'
/** 按工作流隔离并排序,后端数组顺序变化不会影响恢复判断。 */
export function workflowCheckpoints(checkpoints: Checkpoint[], name: string): Checkpoint[] {
return checkpoints
.filter(item => item.workflowName === name)
.toSorted((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt))
}
/** 失败快照可能只有错误;回看最近有效状态,同时只使用最新记录的执行状态。 */
export function breakdownSnapshot(checkpoints: Checkpoint[]): BreakdownState | null {
const records = workflowCheckpoints(checkpoints, 'breakdown')
const latest = records.at(-1)
if (!latest) return null
const data =
records
.slice(-30)
.toReversed()
.find(item => item.state.runConfig || item.state.breakdownResult || item.state.storyboardPlans?.length)
?.state ?? {}
return { ...data, workflowExecution: latest.state.workflowExecution }
}
/** 根据最近后端可恢复窗口推导操作;页面仍需先确认任务已经结束。 */
export function recoveryOptions(checkpoints: Checkpoint[]) {
const records = workflowCheckpoints(checkpoints, 'breakdown').toReversed()
const retry = records.slice(0, 10).some(item => item.state.tasks?.some(task => task.status === 'failed'))
const shots = records
.slice(0, 30)
.some(({ state }) =>
Boolean(
state.storyboardPlans?.length &&
state.subjectCandidates?.length &&
state.subjectForms &&
(state.storyboardEpisodeShots?.length ?? 0) < state.storyboardPlans.length
)
)
const storyboard = records
.slice(0, 10)
.some(({ state }) =>
Boolean(state.storyboardEpisodeShots?.length && state.subjectCandidates?.length && state.subjectForms)
)
return { retry, shots, storyboard }
}
+11
View File
@@ -0,0 +1,11 @@
import type { DramaState } from '../projects/types'
import type { BreakdownState } from '../breakdown/types'
/** 观测接口返回的 checkpoint,保留工作流归属以防混淆两条 graph。 */
export interface Checkpoint {
checkpointId: string
workflowName: string
createdAt: string
metadata?: { nodeName?: string; nodeDurationMs?: number; [key: string]: unknown } | null
state: DramaState & BreakdownState
}