feat: 实现剧本创作与拆解前端工作台
This commit is contained in:
1 parent
edc003443f
commit
2ee6f049f6
56 files changed
+7597
-2
No files matched your search
@@ -0,0 +1,72 @@
|
||||
import type { ProjectStatus } from '../features/projects/types'
|
||||
|
||||
/** 原始项目状态的中文名称。 */
|
||||
export const statusLabels: Record<ProjectStatus, string> = {
|
||||
draft: '草稿',
|
||||
generating: '生成中',
|
||||
completed: '已完成',
|
||||
need_review: '待审核',
|
||||
failed: '生成失败'
|
||||
}
|
||||
|
||||
/** 日期统一使用用户设备所在时区。 */
|
||||
export function formatDate(value?: string): string {
|
||||
if (!value) return '—'
|
||||
const date = new Date(value)
|
||||
return Number.isNaN(date.getTime())
|
||||
? '—'
|
||||
: new Intl.DateTimeFormat('zh-CN', {
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false
|
||||
}).format(date)
|
||||
}
|
||||
|
||||
/** 节点中文名称;未知新节点仍显示原名,方便后端扩展。 */
|
||||
export function nodeLabel(name?: string): string {
|
||||
const labels: Record<string, string> = {
|
||||
createProject: '创建项目',
|
||||
generateCharacter: '角色设定',
|
||||
generateWorld: '世界观',
|
||||
generateEpisode: '编写剧集',
|
||||
reviewDrama: '审核剧本',
|
||||
generateRewriteSuggestion: '改写建议',
|
||||
rewrite: '改写剧本',
|
||||
finishProject: '项目收尾',
|
||||
resumeRewrite: '恢复改写',
|
||||
prepare: '准备分组',
|
||||
prepareRetry: '准备失败重试',
|
||||
summarizeTasks: '汇总抽取任务',
|
||||
extractTask: '执行抽取',
|
||||
mergeMentions: '合并提及',
|
||||
buildProfiles: '整合主体档案',
|
||||
buildSubjects: '构建主体',
|
||||
generateStoryboardPlan: '规划剧情节拍',
|
||||
generateStoryboardShots: '生成分镜',
|
||||
storyboard_shots_progress: '镜头批次已保存',
|
||||
storyboard_ready: '分镜校验完成,准备入库',
|
||||
extract: '模块抽取',
|
||||
merge_mentions: '合并提及',
|
||||
build_profiles: '整合主体档案',
|
||||
build_subjects: '构建主体',
|
||||
generate_storyboard_plan: '规划剧情节拍',
|
||||
generate_storyboard_shots: '生成分镜',
|
||||
completed: '工作流完成',
|
||||
failed: '工作流失败',
|
||||
partial_failed: '部分抽取失败',
|
||||
finalize: '结果入库'
|
||||
}
|
||||
return name ? (labels[name] ?? name) : '状态记录'
|
||||
}
|
||||
|
||||
/** 下载纯文本或 JSON,不将模型内容作为 HTML 渲染。 */
|
||||
export function downloadText(filename: string, content: string, type = 'text/plain;charset=utf-8') {
|
||||
const url = URL.createObjectURL(new Blob([content], { type }))
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = filename.replace(/[<>:"/\\|?*]/g, '_')
|
||||
link.click()
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ApiError, optionalResource, request } from './http'
|
||||
import { projectsApi } from '../features/projects/api'
|
||||
import { breakdownApi } from '../features/breakdown/api'
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('后端 API 契约', () => {
|
||||
it('解包 data,同时保留创建项目的顶层 202 结构', async () => {
|
||||
const fetcher = vi
|
||||
.fn<(url: string, options: RequestInit) => Promise<Response>>()
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: [{ id: 'p1' }] })))
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ projectId: 'p2', status: 'generating' }), { status: 202 })
|
||||
)
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
expect(await projectsApi.list()).toEqual([{ id: 'p1' }])
|
||||
expect(await projectsApi.create({ topic: '故事', style: '悬疑', episodeCount: 3 })).toEqual({
|
||||
projectId: 'p2',
|
||||
status: 'generating'
|
||||
})
|
||||
expect(JSON.parse(fetcher.mock.calls[1]![1].body as string)).toEqual({
|
||||
topic: '故事',
|
||||
style: '悬疑',
|
||||
episodeCount: 3
|
||||
})
|
||||
})
|
||||
|
||||
it('只将缺少 checkpoint 的 404 视为可选结果,保留服务器错误', async () => {
|
||||
expect(await optionalResource(Promise.reject(new ApiError('没有 checkpoint', 404)))).toBeNull()
|
||||
await expect(optionalResource(Promise.reject(new ApiError('数据库异常', 500)))).rejects.toMatchObject({
|
||||
status: 500
|
||||
})
|
||||
})
|
||||
|
||||
it('保留错误细节且拒绝 HTML 代理错误', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi
|
||||
.fn<(url: string, options: RequestInit) => Promise<Response>>()
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ message: '校验失败', issues: ['缺少形态'] }), { status: 400 })
|
||||
)
|
||||
.mockResolvedValueOnce(new Response('<html>Bad Gateway</html>', { status: 502 }))
|
||||
)
|
||||
await expect(request('/projects')).rejects.toMatchObject({ status: 400, details: ['缺少形态'] })
|
||||
await expect(request('/projects')).rejects.toThrow('接口未返回 JSON')
|
||||
})
|
||||
|
||||
it('预览模块使用逗号参数,三种恢复不误发到 start', async () => {
|
||||
const fetcher = vi
|
||||
.fn<(url: string, options: RequestInit) => Promise<Response>>()
|
||||
.mockImplementation(() => Promise.resolve(new Response('{"data":{}}')))
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
await breakdownApi.preview('a/b', { groupSize: 3, modules: ['character', 'scene'] })
|
||||
for (const action of ['retry', 'resume-shots', 'resume-storyboard'] as const)
|
||||
await breakdownApi.run('p', action)
|
||||
expect(fetcher.mock.calls.map(call => call[0])).toEqual([
|
||||
'/api/projects/a%2Fb/breakdown-preview?groupSize=3&modules=character%2Cscene',
|
||||
'/api/projects/p/breakdown/retry',
|
||||
'/api/projects/p/breakdown/resume-shots',
|
||||
'/api/projects/p/breakdown/resume-storyboard'
|
||||
])
|
||||
})
|
||||
|
||||
it('长工作流不使用普通查询的超时,不自动重试 POST', async () => {
|
||||
vi.useFakeTimers()
|
||||
let finish!: (value: Response) => void
|
||||
const fetcher = vi.fn<(url: string, options: RequestInit) => Promise<Response>>().mockImplementation(
|
||||
() =>
|
||||
new Promise<Response>(resolve => {
|
||||
finish = resolve
|
||||
})
|
||||
)
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
const running = breakdownApi.run('p', 'start', { groupSize: 3, modules: ['prop'] })
|
||||
await vi.advanceTimersByTimeAsync(120_000)
|
||||
expect(fetcher).toHaveBeenCalledTimes(1)
|
||||
expect(fetcher.mock.calls[0]![1].signal?.aborted).toBe(false)
|
||||
finish(new Response('{"data":{"workflowExecution":{"status":"failed"}}}'))
|
||||
expect(await running).toMatchObject({ workflowExecution: { status: 'failed' } })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,91 @@
|
||||
/** HTTP 错误携带状态码与后端细节,供页面区别空数据、校验错误与网络故障。 */
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number,
|
||||
public readonly details?: unknown
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'ApiError'
|
||||
}
|
||||
}
|
||||
|
||||
/** 请求选项;长工作流显式关闭超时,不自动重试任何 POST。 */
|
||||
export interface RequestOptions {
|
||||
method?: 'GET' | 'POST'
|
||||
body?: unknown
|
||||
signal?: AbortSignal
|
||||
timeoutMs?: number
|
||||
}
|
||||
|
||||
/** 判断可安全访问键的 JSON 对象。 */
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
/** 兼容普通 {data} 响应,以及 POST /projects 的顶层 202 响应。 */
|
||||
export async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
|
||||
const base = (import.meta.env.VITE_API_BASE_URL || '/api').replace(/\/$/, '')
|
||||
const controller = new AbortController()
|
||||
const timeoutMs = options.timeoutMs ?? 30_000
|
||||
const timer = timeoutMs > 0 ? setTimeout(() => controller.abort(), timeoutMs) : undefined
|
||||
const abort = () => controller.abort()
|
||||
options.signal?.addEventListener('abort', abort, { once: true })
|
||||
if (options.signal?.aborted) controller.abort()
|
||||
try {
|
||||
const response = await fetch(base + path, {
|
||||
method: options.method ?? 'GET',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
...(options.body === undefined ? {} : { 'Content-Type': 'application/json' })
|
||||
},
|
||||
body: options.body === undefined ? undefined : JSON.stringify(options.body),
|
||||
signal: controller.signal
|
||||
})
|
||||
const text = await response.text()
|
||||
let data: unknown
|
||||
try {
|
||||
data = text ? JSON.parse(text) : undefined
|
||||
} catch {
|
||||
throw new ApiError('接口未返回 JSON,请检查 API 地址与代理配置。', response.status)
|
||||
}
|
||||
if (!response.ok) {
|
||||
const message =
|
||||
isRecord(data) && typeof data.message === 'string' ? data.message : `请求失败(${response.status})`
|
||||
throw new ApiError(
|
||||
message,
|
||||
response.status,
|
||||
isRecord(data) ? (data.details ?? data.issues ?? data.error) : data
|
||||
)
|
||||
}
|
||||
return (isRecord(data) && 'data' in data ? data.data : data) as T
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError) throw error
|
||||
if (options.signal?.aborted) throw error
|
||||
if (controller.signal.aborted)
|
||||
throw new ApiError('请求等待超时。后台任务可能仍在运行,请先刷新状态,不要重复提交。', 0)
|
||||
throw new ApiError('无法连接后端。请检查服务与代理;已提交的任务可能仍在运行。', 0)
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
options.signal?.removeEventListener('abort', abort)
|
||||
}
|
||||
}
|
||||
|
||||
/** 仅允许指定的“尚无 checkpoint”404 视为缺省,不吞掉 500 或网络错误。 */
|
||||
export async function optionalResource<T>(promise: Promise<T>): Promise<T | null> {
|
||||
try {
|
||||
return await promise
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.status === 404) return null
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/** 页面统一显示可操作的错误信息。 */
|
||||
export function errorMessage(error: unknown): string {
|
||||
if (error instanceof ApiError && error.details) {
|
||||
const details = typeof error.details === 'string' ? error.details : JSON.stringify(error.details)
|
||||
return `${error.message} ${details}`
|
||||
}
|
||||
return error instanceof Error ? error.message : '操作失败,请刷新后重试。'
|
||||
}
|
||||
Reference in new issue
Block a user