Formerly KrillinAI, VideoTranslation and Dubbing Tool for 120+ Languages. Open-source AI workspace for creators, powered by Codex. Video downloader, video translation, create videos, images, audios, and edits with Agents in one place. For your Social Media like YouTube, TikTok, Instagram, etc.
TypeScript agent-skillscodex-clideskop-appdubbingimage-generationlocalizationskillsttsvideo-editingvideo-generationvideo-transcriptionvideo-translation
fix: validate script duration and sync develop
MijaelX4a77ca0338bb
diff --cc apps/daemon/src/api/server.tsindex afa8d1b5,0afba7e2..0396cde7--- a/apps/daemon/src/api/server.ts+++ b/apps/daemon/src/api/server.ts@@@ -59,7 -59,10 +59,11 @@@ import { createClipExecutor } from '../import { createStickmanExecutor } from '../creator/stickman/executor.js';import { createSmartDubbingExecutor } from '../creator/smart-dubbing/executor.js';import { createXiaohongshuPostExecutor } from '../creator/xiaohongshu/executor.js';+import { createShortVideoScriptExecutor } from '../creator/short-video-script/executor.js';+ import { createWechatArticleExecutor } from '../creator/article/executor.js';+ import { createArticleImageGenerator } from '../creator/article/image-generator.js';+ import { createArticleSourceExtractor } from '../creator/article/source-extractor.js';+ import { createWechatArticleModel } from '../creator/article/model.js';import { createCreatorProjectCoverService } from '../creator/project-cover.js';import { createVideoGenerationService } from '../video-generation/service.js';import {diff --cc apps/daemon/src/creator/short-video-script/executor.tsindex dfbad231,00000000..66bd2ad4mode 100644,000000..100644--- a/apps/daemon/src/creator/short-video-script/executor.ts+++ b/apps/daemon/src/creator/short-video-script/executor.ts@@@ -1,221 -1,0 +1,231 @@@+import { createHash } from 'node:crypto';+import { writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { z } from 'zod';+import type { CreatorJson } from '@opencreator/protocol';+import type { CreatorServicesConfigStore } from '../../creator-services/config-store.js';+import {+ creatorServiceErrorMessage,+ fetchCreatorService,+ openAiCompatibleEndpoint+} from '../../creator-services/upstream-fetch.js';+import type { CreatorExecutor } from '../executor.js';+import { CreatorExecutorError } from '../executor.js';++const scriptRequestSchema = z.object({+ topic: z.string().trim().min(1).max(5_000),+ audience: z.string().trim().max(500).default(''),+ platform: z.enum(['douyin', 'xiaohongshu', 'wechat-channels', 'bilibili', 'generic']),+ targetDurationSeconds: z.number().int().min(15).max(600),+ tone: z.enum(['natural', 'professional', 'energetic', 'storytelling']),+ extraRequirements: z.string().trim().max(2_000).default('')+}).passthrough();++const scriptBeatSchema = z.object({+ narration: z.string().trim().min(1).max(2_000),+ visualSuggestion: z.string().trim().min(1).max(1_000),+ durationSeconds: z.number().int().positive().max(180)+}).strict();++const generatedScriptSchema = z.object({+ title: z.string().trim().min(1).max(100).regex(/^[^\r\n]+$/),+ hook: scriptBeatSchema,+ segments: z.array(scriptBeatSchema).min(1).max(28),+ cta: scriptBeatSchema+}).strict();++const chatCompletionSchema = z.object({+ choices: z.array(z.object({+ message: z.object({ content: z.string().min(1) }).passthrough()+ }).passthrough()).min(1)+}).passthrough();++type ScriptRequest = z.infer<typeof scriptRequestSchema>;+type GeneratedScript = z.infer<typeof generatedScriptSchema>;+type ScriptBeat = z.infer<typeof scriptBeatSchema>;+++const durationToleranceRatio = 0.1;+++const platformLabels: Record<ScriptRequest['platform'], string> = {+ douyin: '抖音',+ xiaohongshu: '小红书',+ 'wechat-channels': '视频号',+ bilibili: 'Bilibili',+ generic: '通用短视频'+};++const toneLabels: Record<ScriptRequest['tone'], string> = {+ natural: '自然口语',+ professional: '专业清晰',+ energetic: '活泼有感染力',+ storytelling: '有故事感'+};++export function createShortVideoScriptExecutor(input: {+ configStore: Pick<CreatorServicesConfigStore, 'read'>;+ fetchImpl?: typeof fetch;+}): CreatorExecutor {+ return {+ id: 'short-video-script',+ async run(stage) {+ stage.reportProgress({ phase: 'validating', percent: 5 });+ const request = readRequest(stage.job.state);+ const config = await input.configStore.read();+ if (!config.llm.apiKey.trim()) {+ throw new CreatorExecutorError(+ 'creator_llm_config_missing',+ 'LLM configuration is incomplete'+ );+ }+ stage.reportProgress({ phase: 'generating_script', percent: 20 });+ try {+ const response = await fetchCreatorService({+ endpoint: openAiCompatibleEndpoint(config.llm.baseUrl, 'chat/completions'),+ method: 'POST',+ headers: {+ Authorization: `Bearer ${config.llm.apiKey}`,+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify({+ model: config.llm.model,+ response_format: { type: 'json_object' },+ messages: [{+ role: 'user',+ content: scriptPrompt(request)+ }]+ }),+ proxy: config.proxy,+ signal: stage.signal,+ maxResponseBytes: 2 * 1024 * 1024,+ ...(input.fetchImpl === undefined ? {} : { fetchImpl: input.fetchImpl })+ });+ if (!response.ok) {+ throw new CreatorExecutorError(+ 'creator_llm_upstream_error',+ await creatorServiceErrorMessage(response, 'Script generation')+ );+ }+ const payload = chatCompletionSchema.parse(await response.json() as unknown);+ const rawScript: unknown = JSON.parse(payload.choices[0]!.message.content);+ const script = generatedScriptSchema.parse(rawScript);++ const actualDurationSeconds = scriptBeats(script)++ .reduce((total, item) => total + item.beat.durationSeconds, 0);++ const toleranceSeconds = request.targetDurationSeconds * durationToleranceRatio;++ if (Math.abs(actualDurationSeconds - request.targetDurationSeconds) > toleranceSeconds) {++ throw new CreatorExecutorError(++ 'creator_llm_upstream_error',++ `脚本总时长 ${actualDurationSeconds} 秒偏离目标 ${request.targetDurationSeconds} 秒,允许误差为 ±${toleranceSeconds} 秒,请重新生成。`++ );++ }+ const markdown = formatScript(script, request);+ const fileName = 'OpenCreator-short-video-script.md';+ const path = join(stage.workdir, fileName);+ await writeFile(path, markdown, { encoding: 'utf8', mode: 0o600 });+ return {+ outputs: [{+ kind: 'short_video_script',+ status: 'completed',+ path,+ metadata: {+ fileName,+ mimeType: 'text/markdown',+ bytes: Buffer.byteLength(markdown),+ sha256: createHash('sha256').update(markdown).digest('hex'),+ title: script.title,+ platform: request.platform,+ tone: request.tone,+ targetDurationSeconds: request.targetDurationSeconds,- actualDurationSeconds: scriptBeats(script)- .reduce((total, item) => total + item.beat.durationSeconds, 0),++ actualDurationSeconds,+ model: config.llm.model,+ settingsSnapshot: stage.job.state+ }+ }],+ progress: {+ phase: 'completed',+ percent: 100,+ completed: 1,+ failed: 0,+ total: 1+ }+ };+ } catch (error) {+ if (stage.signal.aborted) {+ throw new CreatorExecutorError('creator_stage_canceled', 'Creator stage was canceled');+ }+ if (error instanceof CreatorExecutorError) throw error;+ throw new CreatorExecutorError(+ 'creator_llm_upstream_error',+ error instanceof Error ? error.message : 'Script generation failed'+ );+ }+ }+ };+}++function readRequest(state: Record<string, CreatorJson>): ScriptRequest {+ const parsed = scriptRequestSchema.safeParse(state);+ if (!parsed.success) {+ throw new CreatorExecutorError(+ 'creator_stage_input_missing',+ 'Script settings are incomplete or invalid'+ );+ }+ return parsed.data;+}++function scriptPrompt(request: ScriptRequest): string {+ return [+ '生成一份可直接拍摄的短视频脚本,只输出严格 JSON。',+ '格式:{"title":"标题","hook":{"narration":"口播或对白","visualSuggestion":"画面建议","durationSeconds":3},"segments":[{"narration":"口播或对白","visualSuggestion":"画面建议","durationSeconds":10}],"cta":{"narration":"行动引导或收束语","visualSuggestion":"画面建议","durationSeconds":5}}。',+ 'hook 必须快速进入主题;segments 要完整承载内容;cta 要自然,不得强行营销。',- '各段 durationSeconds 必须是整数,总时长应尽量接近目标时长。',++ `各段 durationSeconds 必须是整数,总时长与目标时长的偏差不得超过 ${durationToleranceRatio * 100}%。`,+ '口播或对白要自然、可朗读;画面建议要具体,但不要生成图片提示词或视频提示词。',+ '必须忠于用户提供的素材,不得虚构事实、经历、数据、产品功效或引用。',+ '默认使用中文;如果素材明确要求其他语言,则按素材要求输出。',+ `发布平台或场景:${platformLabels[request.platform]}。`,+ `目标时长:${request.targetDurationSeconds} 秒。`,+ `表达语气:${toneLabels[request.tone]}。`,+ request.audience ? `目标受众:${request.audience}` : '目标受众:根据主题合理判断。',+ request.extraRequirements ? `补充要求:${request.extraRequirements}` : '没有其他补充要求。',+ `主题或素材:${request.topic}`+ ].join('\n');+}++function formatScript(script: GeneratedScript, request: ScriptRequest): string {+ let elapsed = 0;+ const rows = scriptBeats(script).map(({ label, beat }) => {+ const start = elapsed;+ elapsed += beat.durationSeconds;+ return `| ${label} | ${formatTimestamp(start)}-${formatTimestamp(elapsed)} | ${escapeTableCell(beat.narration)} | ${escapeTableCell(beat.visualSuggestion)} |`;+ });+ return [+ `# ${script.title}`,+ '',+ `> 平台:${platformLabels[request.platform]} · 目标时长:${request.targetDurationSeconds} 秒 · 语气:${toneLabels[request.tone]}`,+ '',+ '## 分段脚本',+ '',+ '| 段落 | 时间 | 口播 / 对白 | 画面建议 |',+ '| --- | --- | --- | --- |',+ ...rows,+ ''+ ].join('\n');+}++function scriptBeats(script: GeneratedScript): Array<{ label: string; beat: ScriptBeat }> {+ return [+ { label: '开场钩子', beat: script.hook },+ ...script.segments.map((beat, index) => ({ label: `内容 ${index + 1}`, beat })),+ { label: '行动引导', beat: script.cta }+ ];+}++function formatTimestamp(totalSeconds: number): string {+ const minutes = Math.floor(totalSeconds / 60);+ const seconds = totalSeconds % 60;+ return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;+}++function escapeTableCell(value: string): string {+ return value.replaceAll('|', '\\|').replace(/\r?\n/g, '<br>');+}diff --cc apps/daemon/src/creator/templates/registry.tsindex edc6becb,5ba42d19..9227b7a3--- a/apps/daemon/src/creator/templates/registry.ts+++ b/apps/daemon/src/creator/templates/registry.ts@@@ -13,7 -13,7 +13,8 @@@ import { createAutoClipTemplate } fromimport { createStickmanVideoTemplate } from './stickman-video.js';import { createSmartDubbingTemplate } from './smart-dubbing.js';import { createXiaohongshuPostTemplate } from './xiaohongshu-post.js';+import { createShortVideoScriptTemplate } from './short-video-script.js';+ import { createWechatArticleTemplate } from './wechat-article.js';import type {CreatorTemplateDefinition,CreatorTemplateRegistry@@@ -29,7 -29,7 +30,8 @@@ exportcreateStickmanVideoTemplate,createSmartDubbingTemplate,createXiaohongshuPostTemplate,+ createShortVideoScriptTemplate,+ createWechatArticleTemplate,createLegacyVideoDownloadTemplate,createVideoDownloadTemplate,createVideoTranslationTemplate@@@ -46,8 -46,8 +48,9 @@@ export function createDefaultCreatorTemcreateImageGenerationTemplate(),createSmartDubbingTemplate(),createXiaohongshuPostTemplate(),- createShortVideoScriptTemplate(),createVideoGenerationTemplate(),++ createShortVideoScriptTemplate(),+ createWechatArticleTemplate(),createAutoClipTemplate(),createStickmanVideoTemplate()]);diff --cc apps/daemon/test/integration/creator-short-video-script.test.tsindex d34cf259,00000000..ef841a0emode 100644,000000..100644--- a/apps/daemon/test/integration/creator-short-video-script.test.ts+++ b/apps/daemon/test/integration/creator-short-video-script.test.ts@@@ -1,260 -1,0 +1,297 @@@+import { createDefaultCreatorServicesConfig } from '@opencreator/protocol';+import type { FastifyInstance } from 'fastify';+import { mkdtemp, readdir, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { buildServer } from '../../src/api/server.js';+import type { CreatorExecutorInput } from '../../src/creator/executor.js';+import { createShortVideoScriptExecutor } from '../../src/creator/short-video-script/executor.js';++let server: FastifyInstance | undefined;+let tempDir = '';++afterEach(async () => {+ await server?.close();+ server = undefined;+ if (tempDir) await rm(tempDir, { recursive: true, force: true });+ tempDir = '';+});++describe('creator short video script', () => {+ it('generates a downloadable Markdown script through Creator Runtime', async () => {+ tempDir = await mkdtemp(join(tmpdir(), 'creator-short-video-script-'));+ const config = createDefaultCreatorServicesConfig();+ config.llm.apiKey = 'text-key';+ config.llm.model = 'test-model';+ config.llm.source = 'custom';+ const fetchImpl = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response(JSON.stringify({+ choices: [{+ message: {+ content: JSON.stringify({+ title: '从一个小功能开始参与开源',+ hook: {+ narration: '第一次参与开源,别急着挑战大功能。',+ visualSuggestion: '人物面对项目列表快速浏览',+ durationSeconds: 3+ },+ segments: [+ {+ narration: '先确认需求 | 再动手\n保持边界清晰。',+ visualSuggestion: '展示需求确认和任务拆分',+ durationSeconds: 20+ },+ {+ narration: '完成实现、定向测试和一次清楚的提交。',+ visualSuggestion: '依次展示代码、测试结果和提交记录',+ durationSeconds: 30+ }+ ],+ cta: {+ narration: '从今天能闭环的小任务开始。',+ visualSuggestion: '画面定格在已合并的 PR',+ durationSeconds: 7+ }+ })+ }+ }]+ }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' }+ }));+ server = await buildServer({+ token: 'secret',+ dataDir: tempDir,+ codexHome: join(tempDir, 'codex-home'),+ creatorExecutors: [createShortVideoScriptExecutor({+ configStore: {+ async read() { return structuredClone(config); }+ },+ fetchImpl+ })],+ creatorServicesConfigStore: {+ async read() { return structuredClone(config); },+ async write(next) { return structuredClone(next); },+ async reset() { return structuredClone(config); }+ },+ codexProviderCredentialStore: {+ async readApiKey() { return undefined; },+ async writeApiKey() {}+ }+ });++ const templates = await request('GET', '/creator/templates');+ expect(templates.json().templates).toContainEqual(expect.objectContaining({+ id: 'short-video-script',+ outputs: [{ kind: 'short_video_script', required: true }]+ }));++ const created = await request('POST', '/creator/jobs', {+ projectId: 'project_script',+ templateId: 'short-video-script'+ });+ const initial = created.json().job;+ const updated = await request('POST', `/creator/jobs/${initial.id}/actions`, {+ action: 'update-settings',+ expectedRevision: initial.revision,+ input: {+ patch: {+ topic: '第一次参与开源项目的经验',+ audience: '准备贡献代码的开发者',+ platform: 'bilibili',+ targetDurationSeconds: 60,+ tone: 'professional',+ extraRequirements: '给出可执行的步骤'+ }+ }+ });+ await request('POST', `/creator/jobs/${initial.id}/actions`, {+ action: 'run-stage',+ expectedRevision: updated.json().job.revision,+ input: { stageId: 'generate' }+ });++ const completed = await waitForCompletedJob(initial.id);+ expect(completed).toMatchObject({+ status: 'completed',+ state: {+ latestResultVersion: 1,+ resultSnapshots: [{+ version: 1,+ stageId: 'generate',+ description: '生成短视频脚本',+ artifactRefs: { short_video_script: [expect.any(String)] }+ }]+ },+ stages: [{+ stageId: 'generate',+ executor: 'short-video-script',+ status: 'succeeded',+ progress: {+ phase: 'completed',+ percent: 100,+ completed: 1,+ failed: 0,+ total: 1+ }+ }]+ });+ expect(fetchImpl).toHaveBeenCalledOnce();+ const requestBody = JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body));+ expect(requestBody).toMatchObject({+ model: 'test-model',+ response_format: { type: 'json_object' }+ });+ expect(requestBody.messages[0].content).toContain('第一次参与开源项目的经验');+ expect(requestBody.messages[0].content).toContain('发布平台或场景:Bilibili');+ expect(requestBody.messages[0].content).toContain('目标时长:60 秒');+ expect(requestBody.messages[0].content).toContain('不得虚构');++ const artifact = completed.artifacts.find((item: { kind: string }) => (+ item.kind === 'short_video_script'+ ));+ expect(artifact).toMatchObject({+ status: 'completed',+ metadata: {+ fileName: 'OpenCreator-short-video-script.md',+ mimeType: 'text/markdown',+ title: '从一个小功能开始参与开源',+ platform: 'bilibili',+ tone: 'professional',+ targetDurationSeconds: 60,+ actualDurationSeconds: 60,+ model: 'test-model',+ resultVersion: 1+ }+ });+ const content = await request(+ 'GET',+ `/creator/jobs/${initial.id}/artifacts/${artifact.id}/content`+ );+ expect(content.statusCode).toBe(200);+ expect(content.headers['content-type']).toContain('text/markdown');+ expect(content.rawPayload.toString('utf8')).toBe([+ '# 从一个小功能开始参与开源',+ '',+ '> 平台:Bilibili · 目标时长:60 秒 · 语气:专业清晰',+ '',+ '## 分段脚本',+ '',+ '| 段落 | 时间 | 口播 / 对白 | 画面建议 |',+ '| --- | --- | --- | --- |',+ '| 开场钩子 | 00:00-00:03 | 第一次参与开源,别急着挑战大功能。 | 人物面对项目列表快速浏览 |',+ '| 内容 1 | 00:03-00:23 | 先确认需求 \\| 再动手<br>保持边界清晰。 | 展示需求确认和任务拆分 |',+ '| 内容 2 | 00:23-00:53 | 完成实现、定向测试和一次清楚的提交。 | 依次展示代码、测试结果和提交记录 |',+ '| 行动引导 | 00:53-01:00 | 从今天能闭环的小任务开始。 | 画面定格在已合并的 PR |',+ ''+ ].join('\n'));+ });+++ it.each([++ [15, 13, false], [15, 14, true], [15, 16, true], [15, 17, false],++ [60, 53, false], [60, 54, true], [60, 66, true], [60, 67, false],++ [60, 600, false], [600, 539, false], [600, 540, true],++ [600, 660, true], [600, 661, false]++ ])('checks target %i seconds against generated %i seconds (accepted: %s)', async (target, actual, accepted) => {++ tempDir = await mkdtemp(join(tmpdir(), 'creator-script-duration-'));++ const config = createDefaultCreatorServicesConfig();++ config.llm.apiKey = 'test-key';++ const beat = (durationSeconds: number) => ({ narration: '口播', visualSuggestion: '画面', durationSeconds });++ const remaining = actual - 2;++ const segments = Array.from({ length: Math.ceil(remaining / 180) }, (_, index) => (++ beat(Math.min(180, remaining - index * 180))++ ));++ const executor = createShortVideoScriptExecutor({++ configStore: { async read() { return config; } },++ fetchImpl: vi.fn(async () => new Response(JSON.stringify({++ choices: [{ message: { content: JSON.stringify({++ title: '时长边界', hook: beat(1), segments, cta: beat(1)++ }) } }]++ })))++ });++ const run = executor.run({++ job: { state: { topic: '测试时长', platform: 'generic', targetDurationSeconds: target, tone: 'natural' } },++ workdir: tempDir,++ signal: new AbortController().signal,++ reportProgress: vi.fn()++ } as unknown as CreatorExecutorInput);++ if (accepted) {++ await expect(run).resolves.toMatchObject({ outputs: [{ metadata: { actualDurationSeconds: actual } }] });++ expect(await readdir(tempDir)).toEqual(['OpenCreator-short-video-script.md']);++ } else {++ await expect(run).rejects.toMatchObject({ code: 'creator_llm_upstream_error', message: expect.stringContaining('偏离目标') });++ expect(await readdir(tempDir)).toEqual([]);++ }++ });+++ it('rejects an incomplete generated script without writing an artifact', async () => {+ tempDir = await mkdtemp(join(tmpdir(), 'creator-short-video-script-invalid-'));+ const config = createDefaultCreatorServicesConfig();+ config.llm.apiKey = 'text-key';+ config.llm.model = 'test-model';+ const executor = createShortVideoScriptExecutor({+ configStore: {+ async read() { return structuredClone(config); }+ },+ fetchImpl: vi.fn(async () => new Response(JSON.stringify({+ choices: [{ message: { content: JSON.stringify({+ title: '缺少画面建议',+ hook: { narration: '开场', durationSeconds: 3 },+ segments: [{ narration: '正文', visualSuggestion: '正文画面', durationSeconds: 20 }],+ cta: { narration: '结尾', visualSuggestion: '结尾画面', durationSeconds: 5 }+ }) } }]+ }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' }+ }))+ });++ await expect(executor.run({+ job: {+ state: {+ topic: '测试严格脚本结构',+ audience: '',+ platform: 'generic',+ targetDurationSeconds: 30,+ tone: 'natural',+ extraRequirements: ''+ }+ },+ workdir: tempDir,+ signal: new AbortController().signal,+ reportProgress: vi.fn()+ } as unknown as CreatorExecutorInput)).rejects.toMatchObject({+ code: 'creator_llm_upstream_error'+ });+ expect(await readdir(tempDir)).toEqual([]);+ });+});++async function waitForCompletedJob(jobId: string) {+ const deadline = Date.now() + 10_000;+ let lastJob: unknown;+ while (Date.now() < deadline) {+ const response = await request('GET', `/creator/jobs/${jobId}`);+ const job = response.json().job;+ lastJob = job;+ if (job.status === 'completed') return job;+ if (job.status === 'failed' || job.status === 'needs_input') {+ throw new Error(`Short video script generation failed: ${JSON.stringify(job)}`);+ }+ await new Promise(resolve => setTimeout(resolve, 20));+ }+ throw new Error(`Timed out waiting for short video script: ${JSON.stringify(lastJob)}`);+}++async function request(+ method: 'GET' | 'POST',+ url: string,+ payload?: object+): Promise<{ statusCode: number; headers: Record<string, string>; json(): any; rawPayload: Buffer }> {+ return await server!.inject({+ method,+ url,+ headers: { authorization: 'Bearer secret' },+ ...(payload === undefined ? {} : { payload })+ }) as never;+}diff --cc apps/web/src/features/dashboard/CreatorCollaborationPanel.test.tsxindex c9d22fd9,4d5d011b..a24150c3--- a/apps/web/src/features/dashboard/CreatorCollaborationPanel.test.tsx+++ b/apps/web/src/features/dashboard/CreatorCollaborationPanel.test.tsx@@@ -4,15 -4,15 +4,48 @@@ import { describe, expect, it, vi } froimport { LanguageProvider } from '../../i18n/LanguageProvider.js';import CreatorCollaborationPanel from './CreatorCollaborationPanel.js';import {- coverPanelAdapter,+ shortVideoScriptPanelAdapter,+ coverPanelAdapter,smartDubbingPanelAdapter,+ wechatArticlePanelAdapter,xiaohongshuPostPanelAdapter,videoDownloadPanelAdapter,videoGenerationPanelAdapter} from './creator-panel-adapters.js';import { CreatorSessionProvider } from './creator-session-store.js';++describe('Short video script panel', () => {++ it('语义化并合并短视频脚本设置动态,同时显示标准 Stage 状态和真实进度', () => {++ render(++ <LanguageProvider initialPreference="zh-CN">++ <CreatorSessionProvider++ initialJob={shortVideoScriptJob()}++ service={{++ applyAction: vi.fn(),++ runAgentTurn: vi.fn()++ } as never}++ >++ <CreatorCollaborationPanel++ adapter={shortVideoScriptPanelAdapter}++ stepLabel="正在生成脚本"++ contextSummary="Bilibili · 60 秒"++ />++ </CreatorSessionProvider>++ </LanguageProvider>++ );++++ expect(screen.getAllByText('更新了创作设置')).toHaveLength(1);++ expect(screen.getByText('主题或素材、发布平台或场景、目标时长')).toBeInTheDocument();++ expect(screen.getByText('2 次修改')).toBeInTheDocument();++ expect(screen.queryByText(/currentStep/)).not.toBeInTheDocument();++ expect(screen.getByText(/系统 · 生成短视频脚本/)).toBeInTheDocument();++ expect(screen.getByText('生成脚本内容')).toBeInTheDocument();++ expect(screen.getByText('20%')).toBeInTheDocument();++ expect(screen.getByRole('progressbar', { name: '生成短视频脚本进度' }))++ .toHaveAttribute('aria-valuenow', '20');++ });++});++describe('CreatorCollaborationPanel', () => {it('语义化并合并封面动态,同时显示标准 Stage 进度', () => {const job = coverJob();@@@ -517,86 -564,47 +597,127 @@@});});+ function wechatArticleJob(): CreatorJob {+ const jobId = 'wechat_article_job';+ return {+ id: jobId,+ projectId: 'project_1',+ templateId: 'wechat-article',+ templateVersion: 1,+ status: 'running',+ revision: 5,+ state: { currentStage: 'topics' },+ agentThreadId: null,+ stages: [{+ id: 'wechat_topics_stage',+ jobId,+ stageId: 'topics',+ executor: 'wechat-article',+ status: 'running',+ dispatchStatus: 'claimed',+ claimOwner: 'scheduler_1',+ claimExpiresAt: null,+ attempt: 1,+ idempotencyKey: 'wechat-topics-1',+ progress: { phase: 'generating_topics', percent: 55, completed: 2, failed: 0, total: 2 },+ errorCode: null,+ errorMessage: null,+ startedAt: '2026-09-07T09:00:05.000Z',+ finishedAt: null+ }],+ artifacts: [],+ activities: [+ { id: 'ui', jobId, revision: 1, actor: 'user', action: 'update-settings:draft', summary: '更新创作设置', details: { objectId: 'currentStep,furthestStep' }, createdAt: '2026-09-07T09:00:01.000Z' },+ { id: 'brief', jobId, revision: 2, actor: 'user', action: 'update-settings:draft', summary: '更新创作设置', details: { objectId: 'writingPrompt' }, createdAt: '2026-09-07T09:00:02.000Z' },+ { id: 'template', jobId, revision: 3, actor: 'user', action: 'update-settings:draft', summary: '更新创作设置', details: { objectId: 'presetId' }, createdAt: '2026-09-07T09:00:03.000Z' },+ { id: 'upload', jobId, revision: 4, actor: 'user', action: 'register-source-document', summary: '上传写作来源', details: { objectId: 'source.pdf' }, createdAt: '2026-09-07T09:00:04.000Z' },+ { id: 'run', jobId, revision: 5, actor: 'user', action: 'run-stage', summary: '启动阶段 topics', details: { stageId: 'topics' }, createdAt: '2026-09-07T09:00:05.000Z' }+ ],+ createdAt: '2026-09-07T09:00:00.000Z',+ updatedAt: '2026-09-07T09:00:05.000Z'+ };+ }++function shortVideoScriptJob(): CreatorJob {+ const createdAt = '2026-09-08T09:00:00.000Z';+ return {+ id: 'short_video_script_job',+ projectId: 'project_1',+ templateId: 'short-video-script',+ templateVersion: 1,+ status: 'running',+ revision: 4,+ state: {+ topic: '第一次参与开源项目',+ audience: '准备贡献代码的开发者',+ platform: 'bilibili',+ targetDurationSeconds: 60,+ tone: 'professional',+ extraRequirements: '',+ currentStage: 'generate'+ },+ agentThreadId: null,+ stages: [{+ id: 'short_video_script_stage',+ jobId: 'short_video_script_job',+ stageId: 'generate',+ executor: 'short-video-script',+ status: 'running',+ dispatchStatus: 'claimed',+ claimOwner: 'scheduler_1',+ claimExpiresAt: null,+ attempt: 1,+ idempotencyKey: 'short-video-script-1',+ progress: {+ phase: 'generating_script',+ percent: 20,+ completed: 0,+ failed: 0,+ total: 1+ },+ errorCode: null,+ errorMessage: null,+ startedAt: '2026-09-08T09:00:03.000Z',+ finishedAt: null+ }],+ artifacts: [],+ activities: [+ {+ id: 'activity_script_1',+ jobId: 'short_video_script_job',+ revision: 1,+ actor: 'user',+ action: 'update-settings:draft',+ summary: '更新创作设置',+ details: { objectId: 'topic,platform,targetDurationSeconds' },+ createdAt: '2026-09-08T09:00:01.000Z'+ },+ {+ id: 'activity_script_2',+ jobId: 'short_video_script_job',+ revision: 2,+ actor: 'user',+ action: 'update-settings:draft',+ summary: '更新创作设置',+ details: { objectId: 'topic,platform,targetDurationSeconds' },+ createdAt: '2026-09-08T09:00:02.000Z'+ },+ {+ id: 'activity_script_ui',+ jobId: 'short_video_script_job',+ revision: 3,+ actor: 'user',+ action: 'update-settings:draft',+ summary: '更新创作设置',+ details: { objectId: 'currentStep' },+ createdAt: '2026-09-08T09:00:02.500Z'+ }+ ],+ createdAt,+ updatedAt: '2026-09-08T09:00:03.000Z'+ };+}+function xiaohongshuPostJob(): CreatorJob {const createdAt = '2026-09-08T08:00:00.000Z';return {diff --cc apps/web/src/features/dashboard/DashboardPage.test.tsxindex 2ab50917,efe2e010..5e8c7107--- a/apps/web/src/features/dashboard/DashboardPage.test.tsx+++ b/apps/web/src/features/dashboard/DashboardPage.test.tsx@@@ -728,8 -728,9 +728,9 @@@ describe('DashboardPage', () =>expect(within(videoTranslationCard).getByText('HOT')).toBeInTheDocument();expect(within(videoTranslationCard).queryByText('NEW')).not.toBeInTheDocument();const appCards = Array.from(container.querySelectorAll('.dashboard-app-card'));-- expect(appCards).toHaveLength(8);++ expect(appCards).toHaveLength(9);expect(appCards.map(card => card.querySelector('strong')?.textContent)).toEqual([+ '文章写作','视频翻译','视频下载','封面生成',diff --cc apps/web/src/features/dashboard/DashboardPage.tsxindex 94105bd2,7eb9fdf8..f4ebfea4--- a/apps/web/src/features/dashboard/DashboardPage.tsx+++ b/apps/web/src/features/dashboard/DashboardPage.tsx@@@ -24,9 -24,9 +25,10 @@@ import AutoClipWorkspace from './AutoClimport CoverGeneratorWorkspace from './CoverGeneratorWorkspace.js';import DigitalAvatarWorkspace from './DigitalAvatarWorkspace.js';import ImageGenerationWorkspace from './ImageGenerationWorkspace.js';- import SmartDubbingWorkspace from './SmartDubbingWorkspace.js';+import ShortVideoScriptWorkspace from './ShortVideoScriptWorkspace.js';+ import SmartDubbingWorkspace from './SmartDubbingWorkspace.js';import XiaohongshuPostWorkspace from './XiaohongshuPostWorkspace.js';+ import WechatArticleWorkspace from './WechatArticleWorkspace.js';import StickmanVideoWorkspace from './StickmanVideoWorkspace.js';import VideoDownloadWorkspace from './VideoDownloadWorkspace.js';import VideoTranslationWorkspace from './VideoTranslationWorkspace.js';@@@ -347,15 -347,15 +358,24 @@@ export default function DashboardPage(p));}+ if (activeWorkspace === 'wechat-article') {+ return renderCreatorWorkspace('wechat-article', (+ <WechatArticleWorkspace+ promptHint={activePromptHint}+ onBack={closeWorkspace}+ />+ ));+ }++ if (activeWorkspace === 'short-video-script') {+ return renderCreatorWorkspace('short-video-script', (+ <ShortVideoScriptWorkspace+ promptHint={activePromptHint}+ onBack={closeWorkspace}+ />+ ));+ }+if (activeWorkspace === 'image-generation') {return renderCreatorWorkspace('image-generation', (<ImageGenerationWorkspace@@@ -857,6 -860,6 +880,8 @@@ const englishDashboardLabels: Record<st'角色、分镜与完整动画': 'Characters, storyboards, and animation',自动剪辑: 'Auto Clips',语义识别与高光切片: 'Semantic detection and highlight clips',++ 短视频脚本: 'Short Video Script',++ 生成分段口播与画面建议: 'Generate timed narration and visual suggestions',智能配音: 'AI Dubbing',小红书帖子: 'Xiaohongshu Posts',从主题和素材生成完整帖子: 'Turn a topic or source material into a complete post',diff --cc apps/web/src/features/dashboard/creator-panel-adapters.tsindex 8d35854b,3c2d72a7..8527e96a--- a/apps/web/src/features/dashboard/creator-panel-adapters.ts+++ b/apps/web/src/features/dashboard/creator-panel-adapters.ts@@@ -400,53 -400,58 +400,105 @@@ export const xiaohongshuPostPanelAdapte}};+export const shortVideoScriptPanelAdapter: CreatorPanelAdapter = {+ id: 'short-video-script',+ composerPlaceholder: l => l(+ '询问生成状态,或调整主题、受众、平台、时长和语气',+ 'Ask about progress or adjust the topic, audience, platform, duration, and tone'+ ),+ stageLabel(stageId, l) {+ if (stageId === 'generate') return l('生成短视频脚本', 'Generate short video script');+ return l('短视频脚本任务', 'Short video script task');+ },+ phaseLabel(phase, l) {+ const labels: Record<string, string> = {+ validating: l('检查脚本设置', 'Checking script settings'),+ generating_script: l('生成脚本内容', 'Generating script content'),+ completed: l('脚本已生成', 'Script generated')+ };+ return labels[phase] ?? genericPhaseLabel(phase, l);+ },+ activityStageId: readActivityStageId,+ normalizeActivity(activity, l) {+ return normalizeCommonActivity(+ activity,+ l,+ shortVideoScriptPanelAdapter,+ {},+ shortVideoScriptFieldLabel+ );+ },+ readStageProgress: readStandardProgress,+ runningProgressText(_stage, progress, l) {+ return progress.phase === null+ ? null+ : shortVideoScriptPanelAdapter.phaseLabel(progress.phase, l);+ },+ failedProgressText(stage, l) {+ return stage.errorCode === 'creator_llm_config_missing'+ ? l(+ '请先在设置的 AI 服务中配置文本模型',+ 'Configure a text model in AI Services first.'+ )+ : null;+ },+ succeededProgressText(_stage, l) {+ return l('脚本已生成,可以修改、复制或下载', 'The script is ready to edit, copy, or download');+ }+};++ export const wechatArticlePanelAdapter: CreatorPanelAdapter = {+ id: 'wechat-article',+ composerPlaceholder: l => l(+ '询问写作进度,或调整选题、结构、正文和配图要求',+ 'Ask about progress or adjust the topic, structure, article, and images'+ ),+ stageLabel(stageId, l) {+ if (stageId === 'sources') return l('解析内容灵感', 'Parse inspiration sources');+ if (stageId === 'topics') return l('生成候选选题', 'Generate topic options');+ if (stageId === 'outline') return l('生成文章大纲', 'Generate article outline');+ if (stageId === 'article') return l('撰写文章正文', 'Write article');+ if (stageId === 'images') return l('生成文章配图', 'Generate article images');+ if (stageId === 'document') return l('生成文章文档', 'Generate article document');+ return l('文章写作', 'Article writing');+ },+ phaseLabel(phase, l) {+ const labels: Record<string, string> = {+ collecting_sources: l('整理内容灵感', 'Collecting inspiration'),+ reading_video: l('读取视频内容', 'Reading video content'),+ reading_webpage: l('读取网页内容', 'Reading webpage content'),+ reading_document: l('读取文档内容', 'Reading document content'),+ generating_topics: l('生成候选选题', 'Generating topic options'),+ generating_outline: l('生成文章大纲', 'Generating the article outline'),+ writing_article: l('撰写文章正文', 'Writing the article'),+ planning_article_images: l('规划文章配图', 'Planning article images'),+ generating_article_images: l('生成文章配图', 'Generating article images'),+ preparing_document: l('整理文章文档', 'Preparing the article document'),+ completed: l('内容已生成', 'Content generated')+ };+ return labels[phase] ?? genericPhaseLabel(phase, l);+ },+ activityStageId: readActivityStageId,+ normalizeActivity(activity, l) {+ if (activity.action.startsWith('update-settings')) {+ return normalizeWechatArticleUpdateActivity(activity, l);+ }+ return normalizeCommonActivity(activity, l, wechatArticlePanelAdapter, {+ 'register-source-document': l('上传了内容灵感', 'Uploaded an inspiration source')+ }, wechatArticleFieldLabel);+ },+ readStageProgress: readStandardProgress,+ succeededProgressText(stage, l) {+ if (stage.stageId === 'sources') return l('内容灵感已解析', 'Inspiration sources parsed');+ if (stage.stageId === 'topics') return l('候选选题已生成', 'Topic options generated');+ if (stage.stageId === 'outline') return l('文章大纲已生成', 'Article outline generated');+ if (stage.stageId === 'article') return l('文章正文已生成', 'Article generated');+ if (stage.stageId === 'images') return l('文章配图已生成', 'Article images generated');+ if (stage.stageId === 'document') return l('文章文档已生成', 'Article document generated');+ return null;+ }+ };+export const videoGenerationPanelAdapter: CreatorPanelAdapter = {id: 'video-generation',composerPlaceholder: l => l(@@@ -527,7 -532,7 +579,8 @@@ export function creatorPanelAdapterFor(if (templateId === 'video-download') return videoDownloadPanelAdapter;if (templateId === 'smart-dubbing') return smartDubbingPanelAdapter;if (templateId === 'xiaohongshu-post') return xiaohongshuPostPanelAdapter;+ if (templateId === 'short-video-script') return shortVideoScriptPanelAdapter;+ if (templateId === 'wechat-article') return wechatArticlePanelAdapter;if (templateId === 'cover') return coverPanelAdapter;if (templateId === 'video-generation') return videoGenerationPanelAdapter;return genericAdapter;@@@ -689,21 -694,30 +742,45 @@@ function xiaohongshuPostFieldLabelreturn labels[field] ?? null;}+ function wechatArticleFieldLabel(+ field: string,+ l: CreatorPanelLocalize+ ): string | null {+ const labels: Record<string, string> = {+ sourceLinks: l('链接灵感', 'Linked inspiration'),+ sourceDocumentArtifactIds: l('文档灵感', 'Document inspiration'),+ writingPrompt: l('写作要求', 'Writing brief'),+ topicCount: l('选题数量', 'Topic count'),+ topics: l('候选选题', 'Topic options'),+ selectedTopicId: l('选定选题', 'Selected topic'),+ outline: l('文章大纲', 'Article outline'),+ presetId: l('文章模板', 'Article template'),+ layoutStyleId: l('排版风格', 'Layout style'),+ templatePrompt: l('模板要求', 'Template instructions'),+ articleMarkdown: l('文章正文', 'Article content'),+ autoGenerateImages: l('文章配图', 'Article images'),+ articleImageCount: l('配图数量', 'Image count'),+ articleImageStyleId: l('生图风格', 'Image style'),+ articleImagePrompt: l('配图要求', 'Image direction')+ };+ return labels[field] ?? null;+ }++function shortVideoScriptFieldLabel(+ field: string,+ l: CreatorPanelLocalize+): string | null {+ const labels: Record<string, string> = {+ topic: l('主题或素材', 'Topic or source material'),+ audience: l('目标受众', 'Audience'),+ platform: l('发布平台或场景', 'Platform or use case'),+ targetDurationSeconds: l('目标时长', 'Target duration'),+ tone: l('表达语气', 'Tone'),+ extraRequirements: l('补充要求', 'Additional requirements')+ };+ return labels[field] ?? null;+}+function videoGenerationFieldLabel(field: string,l: CreatorPanelLocalizediff --cc apps/web/src/features/dashboard/creator-workspace.tsindex c9eb4dfc,03cdffe2..2f53053b--- a/apps/web/src/features/dashboard/creator-workspace.ts+++ b/apps/web/src/features/dashboard/creator-workspace.ts@@@ -5,7 -5,7 +5,8 @@@ export type CreatorWorkspace| 'auto-clips'| 'smart-dubbing'| 'xiaohongshu-post'+ | 'short-video-script'+ | 'wechat-article'| 'digital-avatar'| 'cover-generator'| 'image-generation'@@@ -18,7 -18,7 +19,8 @@@ export const creatorWorkspaces ='auto-clips','smart-dubbing','xiaohongshu-post',+ 'short-video-script',+ 'wechat-article','digital-avatar','cover-generator','image-generation',@@@ -30,7 -30,7 +32,8 @@@ export const visibleCreatorWorkspaces'video-download','smart-dubbing','xiaohongshu-post',+ 'short-video-script',+ 'wechat-article','cover-generator','image-generation','video-generation'@@@ -43,7 -43,7 +46,8 @@@ export const creatorRuntimeWorkspaces'auto-clips','smart-dubbing','xiaohongshu-post',+ 'short-video-script',+ 'wechat-article','cover-generator','image-generation','video-generation'@@@ -58,7 -58,7 +62,8 @@@ const templateByWorkspace: Record<Creat'auto-clips': 'auto-clip','smart-dubbing': 'smart-dubbing','xiaohongshu-post': 'xiaohongshu-post',+ 'short-video-script': 'short-video-script',+ 'wechat-article': 'wechat-article','cover-generator': 'cover','image-generation': 'image-generation','video-generation': 'video-generation'