import {useEffect, useRef, useState} from 'react'; import type {NPConfig, NPRun, NPSchema, NPValue} from './contract.ts'; import {getCatalog, getGenSchema, getJSON} from './api.ts'; import {generationError, postNP, runFinished, schemaDefaults, setConfigPath} from './generation-logic.ts'; import type {NPPlan} from '../np-contract.ts'; import {QuotaTree} from './QuotaTree.tsx'; import {AssetCatalog, SceneCatalog} from './Catalog.tsx'; import type {QuotaTargets} from './quota.ts'; import {versionLabel} from './quota.ts'; import {BatchDesigner} from './BatchDesigner.tsx'; import {SegmentConfig} from './SegmentConfig.tsx'; import {addArrangement, batchTotal, defaultBatch, freshSeed, missingGroupFields, setArrangementLabels, toggleScene} from './np-batch.ts'; import type {BatchSettings, ExpandedConfig, GenSchema, SingleConfig} from './np-batch.ts'; const storageKey = 'np-batch-config/3'; const states: Record = {queued: '等待', running: '进行中', done: '完成', failed: '失败', generating: '生成中', generated: '已生成', converted: '已转换', completed: '完成', completed_with_failures: '完成,部分失败'}; const renders: Record = {rendered: '已渲染', render_failed: '渲染失败', skipped: '未渲染'}; const arrangementDescriptions: Record = {covisible_region: '两路同时看到同一块地方', covisible_event: '只发生一次、两路都看到', observer_body: '一路的画面里出现另一路的机身', target_visible: '目标在视场里连续可见的最短时长'}; export function GenerationSwitch({active}: {active: 'config' | 'results'}) { return
配置结果生成配置台:{active === 'config' ? '先配置,右侧实时预估' : '看这批出了多少、丢在哪'}
; } function ArrangementIcon({kind}: {kind: string}) { return ; } export function GenerationConfig() { const [schema, setSchema] = useState(null), [config, setConfig] = useState(null); const [plan, setPlan] = useState(null), [planning, setPlanning] = useState(false), [error, setError] = useState(''); const [draft, setDraft] = useState(''), [copied, setCopied] = useState(''); const [run, setRun] = useState(null), [starting, setStarting] = useState(false), [runError, setRunError] = useState(''), [pollRetry, setPollRetry] = useState(0); const [renderVideo, setRenderVideo] = useState(true); const [genSchema, setGenSchema] = useState(null); const [readyScenes, setReadyScenes] = useState(null), [genError, setGenError] = useState(''), [genRetry, setGenRetry] = useState(0); const [selectedConfig, setSelectedConfig] = useState(null); const focused = useRef(''), seeded = useRef(false), submitLock = useRef(false), submitController = useRef(null), [planRetry, setPlanRetry] = useState(0); useEffect(() => { const controller = new AbortController(); setGenError(''); setGenSchema(null); Promise.all([getGenSchema(controller.signal), getCatalog()]).then(([value, catalog]) => { if (!controller.signal.aborted) {setArrangementLabels(value.arrangement_labels); setGenSchema(value); setReadyScenes(catalog.scenes.filter(scene => scene.capability_ready).map(scene => scene.id));} }).catch(e => {if (!controller.signal.aborted) setGenError(generationError(e));}); return () => controller.abort(); }, [genRetry]); // 批量设定只有 config.batch 一份(np-batch-config/3):没存过就按能用的场景给一份默认分布 useEffect(() => { if (genSchema && readyScenes && config && !seeded.current) { seeded.current = true; if (!(config.batch as BatchSettings | undefined)?.scenes?.length) setConfig(current => current && setConfigPath(current, ['batch'], defaultBatch(readyScenes) as unknown as NPValue)); } }, [genSchema, readyScenes, config]); useEffect(() => { const controller = new AbortController(); getJSON('/api/v1/np/schema', controller.signal).then(value => { if (controller.signal.aborted) return; let initial = schemaDefaults(value) as NPConfig; try {const saved = JSON.parse(localStorage.getItem(storageKey) || 'null'); if (saved?.schema === initial.schema) initial = saved;} catch { /* Defaults survive corrupt or unavailable storage. */ } setSchema(value); setConfig(initial); try {const id = sessionStorage.getItem('np-active-run'); if (id) getJSON('/api/v1/np/runs/' + encodeURIComponent(id), controller.signal).then(setRun).catch(e => {if (!controller.signal.aborted) setRunError(generationError(e));});} catch { /* Storage is optional. */ } }).catch(e => {if (!controller.signal.aborted) setError(generationError(e));}); return () => {controller.abort(); submitController.current?.abort();}; }, []); useEffect(() => { if (!config) return; const controller = new AbortController(); setPlanning(true); setPlan(null); setError(''); setCopied(''); setDraft(JSON.stringify(config, null, 2)); try {localStorage.setItem(storageKey, JSON.stringify(config));} catch { /* Planning does not depend on storage. */ } const timer = setTimeout(() => {postNP('/api/v1/np/plan', config, controller.signal).then(value => {if (!controller.signal.aborted) {setPlan(value); setPlanning(false);}}).catch(e => {if (!controller.signal.aborted) {setError(generationError(e)); setPlanning(false);}});}, 120); return () => {controller.abort(); clearTimeout(timer);}; }, [config, planRetry]); useEffect(() => { if (!run || runFinished(run)) return; const controller = new AbortController(); const timer = setTimeout(() => {getJSON('/api/v1/np/runs/' + encodeURIComponent(run.id), controller.signal).then(value => {if (!controller.signal.aborted) {setRun(value); setRunError('');}}).catch(e => {if (!controller.signal.aborted) {setRunError(generationError(e)); setPollRetry(x => x + 1);}});}, 1000); return () => {controller.abort(); clearTimeout(timer);}; }, [run, pollRetry]); useEffect(() => {if (plan) {const focus = new URLSearchParams(location.hash.split('?')[1]).get('focus'); if (focus && focus !== focused.current) {const node = document.getElementById('np-' + focus); if (node) {node.scrollIntoView({block: 'center'}); focused.current = focus;}}}}, [plan]); if (!schema || !config) return
{error ?

{error}

:

读取生成配置…

}
; const change = (path: string[], value: NPValue) => setConfig(current => current && setConfigPath(current, path, value)); const commands = plan?.commands, command = commands ? [...commands.generate.slice(0, 3), `共 ${commands.generate_total} 段`, '', commands.questions, '', commands.convert].join('\n') : '规划完成后显示生成、出题和转换命令'; const families = schema['x-families'] || []; const batch = config.batch as BatchSettings | undefined, missing = batch?.scenes ? missingGroupFields(batch) : []; const total = batch?.scenes && !missing.length ? batchTotal(batch) : 0, busy = !plan || starting || !!run && !runFinished(run); // 试跑 1 段、整批、单段都走同一个接口:limit 是按场景、组轮流取的前几段;segment 是第 4 卡的一段(可能手改过),只跑它 // whole: the whole batch started, so the stored seed moves on and the next batch draws new scripts; a trial keeps it so the // whole batch that follows reproduces the tried segment async function startRun(limit: number, segment?: SingleConfig, whole = false) { if (submitLock.current || !config) return; submitLock.current = true; setStarting(true); setRunError(''); const controller = new AbortController(); submitController.current = controller; try {const value = await postNP('/api/v1/np/runs', {config, limit, render: renderVideo, ...(segment ? {segment} : {})}, controller.signal); if (!controller.signal.aborted) {setRun(value); if (whole) setConfig(current => current && setConfigPath(current, ['batch', 'seed'], freshSeed())); try {sessionStorage.setItem('np-active-run', value.id);} catch { /* Optional recovery. */ }}} catch (e) {if (!controller.signal.aborted) {setRunError(generationError(e)); if (String(e).includes('BATCH_REPEATS')) setConfig(current => current && setConfigPath(current, ['batch', 'seed'], freshSeed()));}} finally {submitLock.current = false; if (!controller.signal.aborted) setStarting(false);} } async function applyJSON() { try {const value = JSON.parse(draft); await postNP('/api/v1/np/validate', value); setConfig(value); setPlanRetry(x => x + 1);} catch (e) {setError(generationError(e)); setPlan(null);} } function download() { const url = URL.createObjectURL(new Blob([JSON.stringify(config, null, 2) + '\n'], {type: 'application/json'})), link = document.createElement('a'); link.href = url; link.download = 'batch.json'; link.click(); URL.revokeObjectURL(url); } function arrangements() { return
版本要的安排

由所选版本的有效条件与视频要求推出。每组任选一种满足;不同组分别满足。安排在第 3 卡各组的“情形安排”里设。

{plan ? plan.arrangements.map(row => { const versions = families.flatMap(f => f.versions), selected = versions.filter(v => row.version_ids.includes(v.id) || row.version_ids.includes(v.version_id || '')), multi = selected.filter(v => v.videos.length > 1).length; const who = selected.length === versions.length ? '全部版本' : selected.length && multi === selected.length ? '多机身版本要用' : selected.length && !multi ? '单机身版本要用' : `${row.version_ids.length} 个版本要用`; return
{row.label}{arrangementDescriptions[row.kind]}{row.version_ids.length} 版关联{who}{row.generator_type == null ? 生成器还不会安排 : row.in_batch ? 批量里有 : }
; }) :

{planning ? '规划中…' : '有效配置下由 np plan 返回安排。'}

}
按版本查看“任选一种”
{plan?.arrangement_requirements.map((group, i) =>

{versionLabel(families, group.version_id)}
{group.any_of.length > 1 ? '任选一种:' : '需要:'}{group.any_of.map(key => schema?.['x-arrangement-labels']?.[key] || key).join(' 或 ')}
{group.source}

)}
; } const updateBatch = (value: BatchSettings) => {change(['batch'], value as unknown as NPValue); setSelectedConfig(null);}; const unavailable =

{genError || '读取生成器配置和资料…'}{genError && <> }

; return

1要哪些题

按总数、母题、子题、问法和版本分配题数;修改上层会均分给未锁定项,下层可微调。

change(['targets'], targets)} />

2可用资源

scene.scene) : []} onToggle={id => {if (batch) updateBatch(toggleScene(batch, id));}}/>
动态资产(人形、机器狗、观察者)

3批量设定

{genSchema && readyScenes && batch?.scenes ? (missing.length ?

批量设定缺:{missing.join('、')}。点“恢复默认”,或在高级参数 JSON 里补上。

: ) : unavailable}

4单段配置

{genSchema && batch ? selectedConfig ? void startRun(1, segment)}/> :

在上面展开后点一行

: unavailable}

5版本要的安排

{arrangements()}
高级参数 JSON · 同一 schema 校验