Show it a video you love. Get a new video in the same style. An AI crew (Claude Code or Codex) plans, builds and reviews it with you.
JavaScript 2d-animationai-agentsai-videoanimationclaude-codecodexmulti-agentstyle-transfervideo-generation
Per-project review round limits; easier required-input uploads
許元豪77dfe624077c
diff --git a/app/server/index.mjs b/app/server/index.mjsindex cbc4d82..7d30267 100644--- a/app/server/index.mjs+++ b/app/server/index.mjs@@ -3,7 +3,7 @@import './env.mjs'; // first: API keys / tool paths from ~/.reelmimic/secrets.jsonimport express from 'express';import multer from 'multer';-import { existsSync, mkdirSync, renameSync } from 'node:fs';+import { existsSync, mkdirSync, renameSync, unlinkSync } from 'node:fs';import { join, extname, resolve, sep } from 'node:path';import { agentStatus } from './agents/index.mjs';import * as J from './jobs.mjs';@@ -34,8 +34,12 @@ app.post('/api/projects', upload.fields([{ name: 'reference', maxCount: 1 }, { nif (!ref && !isUrl(url)) return res.status(400).json({ error: '請上傳參考影片或貼上影片連結' });if (!['claude', 'codex'].includes(agent)) return res.status(400).json({ error: 'agent 必須是 claude 或 codex' });if (/�/.test(brief + (title || ''))) return res.status(400).json({ error: '需求文字編碼錯誤(請用 UTF-8 送出)' });+ // optional review/fix round limits for this project (castRounds, chunkRounds, finalRounds: whole numbers 1–10)+ let settings;+ try { settings = Object.fromEntries(Object.entries(J.cleanRounds(req.body)).filter(([, v]) => v != null)); }+ catch (e) { for (const f of Object.values(req.files || {}).flat()) try { unlinkSync(f.path); } catch {} return res.status(400).json({ error: e.message }); }const id = slug();- const job = J.createJob({ id, title: (title || brief.split('\n')[0] || '未命名').slice(0, 40), agent, brief, lang,+ const job = J.createJob({ id, title: (title || brief.split('\n')[0] || '未命名').slice(0, 40), agent, brief, lang, settings,reference: ref ? { type: 'file', src: 'inputs/reference' + (extname(ref.originalname) || '.mp4') } : { type: 'url', src: url.trim() } });if (ref) renameSync(ref.path, join(J.dirOf(id), job.reference.src));for (const f of req.files?.inputs || []) renameSync(f.path, join(J.dirOf(id), 'inputs', fileName(f)));@@ -47,7 +51,7 @@ app.get('/api/projects/:id', (req, res) => { if (guard(res, req.params.id)) res.// Extra inputs later (e.g. the user finds their song file during plan review).// ?to=attachments → chat attachments (inputs/attachments/, timestamped so repeats don't overwrite); returns the saved paths-app.post('/api/projects/:id/inputs', upload.array('inputs', 20), (req, res) => {+app.post('/api/projects/:id/inputs', upload.array('inputs', 20), async (req, res) => {if (!guard(res, req.params.id)) return;const attach = req.query.to === 'attachments', sub = attach ? join('inputs', 'attachments') : 'inputs';mkdirSync(join(J.dirOf(req.params.id), sub), { recursive: true });@@ -56,6 +60,10 @@ app.post('/api/projects/:id/inputs', upload.array('inputs', 20), (req, res) => {const name = (attach ? `${Date.now().toString(36)}_` : '') + fileName(f);renameSync(f.path, join(J.dirOf(req.params.id), sub, name)); saved.push(`${sub.split(sep).join('/')}/${name}`);}+ // ?for=<required input id>: these files answer that item (any file name); lyrics text/timing is handled there+ if (!attach && req.query.for) J.provideInput(req.params.id, String(req.query.for), saved);+ else if (!attach) J.alignIfReady(req.params.id).catch(() => null); // background: lyrics waiting for music+ J.touch(req.params.id);res.json({ ...J.snapshot(req.params.id), saved });});@@ -81,8 +89,14 @@ app.post('/api/projects/:id/lyrics', async (req, res) => {res.json(await J.saveLyrics(id, text));});app.post('/api/projects/:id/waive', (req, res) => { const { id } = req.params; if (!guard(res, id)) return; J.waive(id, String(req.body?.input || '')); res.json(J.snapshot(id)); });+app.post('/api/projects/:id/unwaive', (req, res) => { const { id } = req.params; if (!guard(res, id)) return; J.unwaive(id, String(req.body?.input || '')); res.json(J.snapshot(id)); });app.post('/api/projects/:id/resume', act(J.resume));app.post('/api/projects/:id/accept', act(J.accept));+// Review/fix round limits for this project. Allowed any time (also while agents work): the next check uses the new value.+app.post('/api/projects/:id/settings', (req, res) => {+ if (!guard(res, req.params.id)) return;+ try { res.json(J.setRounds(req.params.id, req.body || {})); } catch (e) { res.status(400).json({ error: e.message }); }+});app.get('/api/config', (req, res) => res.json(J.CONFIG));app.post('/api/projects/:id/retry', act(J.retry));app.post('/api/projects/:id/critique', act(J.critique));diff --git a/app/server/jobs.mjs b/app/server/jobs.mjsindex 73acc46..5a1972c 100644--- a/app/server/jobs.mjs+++ b/app/server/jobs.mjs@@ -38,6 +38,30 @@ export const CONFIG = {maxAgentsGlobal: +(process.env.MAX_AGENTS || 12), // all projects together (CLI rate limits, CPU/GPU for renders)};+// Review/fix round limits: CONFIG holds the defaults; a project can set its own (job.settings), read at every check so a+// change applies from the next round on. When a limit is reached the job pauses for the user instead of looping.+export const ROUND_KEYS = ['castRounds', 'chunkRounds', 'finalRounds'];+export const ROUND_RANGE = { min: 1, max: 10 };+export function rounds(id) { const s = load(id).settings || {}; return Object.fromEntries(ROUND_KEYS.map((k) => [k, s[k] ?? CONFIG[k]])); }+// Validates { castRounds?, chunkRounds?, finalRounds? } (whole numbers 1–10; '' / null = back to the default). Throws on bad input.+export function cleanRounds(input = {}) {+ const out = {};+ for (const k of ROUND_KEYS) {+ if (!(k in input)) continue;+ const raw = input[k];+ if (raw === '' || raw == null) { out[k] = null; continue; }+ const v = Number(raw);+ if (!Number.isInteger(v) || v < ROUND_RANGE.min || v > ROUND_RANGE.max) throw new Error(`${k} must be a whole number from ${ROUND_RANGE.min} to ${ROUND_RANGE.max}`);+ out[k] = v;+ }+ return out;+}+export function setRounds(id, input) {+ const clean = cleanRounds(input);+ update(id, (x) => { const s = { ...(x.settings || {}) }; for (const [k, v] of Object.entries(clean)) { if (v == null) delete s[k]; else s[k] = v; } x.settings = s; });+ return snapshot(id);+}+export const bus = new EventEmitter(); bus.setMaxListeners(100);const running = new Map(); // id → Set<AbortController>// Stop every agent this server started (on shutdown), so none keeps working unseen after a restart.@@ -106,14 +130,15 @@ export function snapshot(id) {production: readJSON(join(d, 'build', 'production.json')),lyrics: readJSON(join(d, 'analysis', 'lyrics', 'subs.json')),requiredInputs: requiredInputs(id, plan, job),+ rounds: { values: rounds(id), defaults: Object.fromEntries(ROUND_KEYS.map((k) => [k, CONFIG[k]])), ...ROUND_RANGE },inputs: list('inputs', /./),};}-export function createJob({ id, title, agent, brief, reference, lang = 'zh-TW' }) {+export function createJob({ id, title, agent, brief, reference, lang = 'zh-TW', settings = {} }) {const d = dirOf(id); mkdirSync(join(d, 'inputs'), { recursive: true }); mkdirSync(join(d, 'analysis'), { recursive: true });writeFileSync(join(d, 'brief.md'), brief || '');- const job = { id, title, agent, lang, reference, stage: 'new', sessionId: null, sessions: {}, createdAt: now(), chat: [], log: [], needs: [], waived: [], pipeline: {} };+ const job = { id, title, agent, lang, reference, settings, stage: 'new', sessionId: null, sessions: {}, createdAt: now(), chat: [], log: [], needs: [], waived: [], pipeline: {} };save(job);return job;}@@ -129,26 +154,56 @@ function requiredInputs(id, plan, job) {const d = dirOf(id), files = existsSync(join(d, 'inputs')) ? readdirSync(join(d, 'inputs')) : [];return (plan?.required_inputs || []).map((r) => {let status = 'missing';+ const given = (job.provided?.[r.id] || []).filter((f) => existsSync(join(d, f)));if ((job.waived || []).includes(r.id)) status = 'waived';- else if (r.kind === 'lyrics' && (existsSync(join(d, 'analysis', 'lyrics', 'subs.lrc')) || files.some((f) => /\.lrc$/i.test(f)))) status = 'provided';+ else if (given.length) status = 'provided'; // uploaded for this item from the web app+ else if (r.kind === 'lyrics' && (existsSync(join(d, 'inputs', 'lyrics.txt')) || existsSync(join(d, 'analysis', 'lyrics', 'subs.lrc')) || files.some((f) => /\.lrc$/i.test(f)))) status = 'provided';else if (r.file && existsSync(join(d, r.file))) status = 'provided';else if (r.kind !== 'lyrics' && files.some((f) => f.toLowerCase().includes((r.match || r.id).toLowerCase()))) status = 'provided';- return { ...r, status };+ return { ...r, status, files: given };});}export function openInputs(id) { const s = snapshot(id); return s.requiredInputs.filter((r) => r.status === 'missing'); }export function waive(id, inputId) { update(id, (j) => { j.waived = [...new Set([...(j.waived || []), inputId])]; j.needs = (j.needs || []).filter((n) => n.input !== inputId); }); }+export function unwaive(id, inputId) { update(id, (j) => { j.waived = (j.waived || []).filter((x) => x !== inputId); }); }+export function touch(id) { update(id, () => {}); } // tell open pages to reload (e.g. after files were added)++// Files uploaded for one required input (inputs/…): remember which item they answer, so any file name counts.+// A .txt for a lyrics item is taken as the lyric text. Then time the lyrics if the music is there now.+export function provideInput(id, inputId, saved) { // records the answer now; lyric timing (≈1 min) runs in the background+ const d = dirOf(id), r = (readJSON(join(d, 'plan.json'))?.required_inputs || []).find((x) => x.id === inputId);+ if (!r || !saved.length) return false;+ update(id, (j) => { j.provided = { ...(j.provided || {}), [inputId]: saved }; j.waived = (j.waived || []).filter((x) => x !== inputId); });+ const txt = r.kind === 'lyrics' && saved.find((f) => /\.txt$/i.test(f)), text = txt && !/(^|\/)lyrics\.txt$/i.test(txt) ? readText(join(d, txt)) : null;+ (text?.trim() ? saveLyrics(id, text) : alignIfReady(id)).catch((e) => console.error(e));+ return true;+}+// Lyrics pasted before the music arrived are only text: time them as soon as there is audio (and again before production).+export async function alignIfReady(id) {+ const d = dirOf(id);+ if (!existsSync(join(d, 'inputs', 'lyrics.txt')) || existsSync(join(d, 'analysis', 'lyrics', 'subs.lrc')) || !musicFile(id)) return null;+ return saveLyrics(id, readText(join(d, 'inputs', 'lyrics.txt')));+}+// The song to time lyrics against: the plan's music file, else a file the user uploaded for an audio item, else any audio in inputs/.+function musicFile(id) {+ const d = dirOf(id), plan = readJSON(join(d, 'plan.json')) || {}, job = load(id), AUD = /\.(mp3|m4a|wav|aac|flac|ogg|opus|mp4|mov|webm)$/i;+ if (plan.music?.file && existsSync(join(d, plan.music.file))) return plan.music.file;+ const audioIds = (plan.required_inputs || []).filter((r) => r.kind === 'audio').map((r) => r.id);+ for (const k of audioIds) for (const f of job.provided?.[k] || []) if (AUD.test(f) && existsSync(join(d, f))) return f;+ const f = existsSync(join(d, 'inputs')) ? readdirSync(join(d, 'inputs')).find((x) => AUD.test(x) && !/^reference\./i.test(x)) : null;+ return f ? `inputs/${f}` : null;+}// The user pastes lyrics (their text) → inputs/lyrics.txt → timed against the plan's music section → analysis/lyrics/subs.lrcexport function saveLyrics(id, text) {const d = dirOf(id); writeFileSync(join(d, 'inputs', 'lyrics.txt'), text.trim() + '\n');const plan = readJSON(join(d, 'plan.json')) || {}, m = plan.music || {};- const audio = m.file && existsSync(join(d, m.file)) ? join(d, m.file) : null;+ const song = musicFile(id), audio = song ? join(d, song) : null;const out = join(d, 'analysis', 'lyrics'); mkdirSync(out, { recursive: true });- if (!audio) { log(id, { type: 'text', text: '歌詞已存,等企劃決定配樂段落後再對時' }); return Promise.resolve({ ok: true, aligned: false }); }+ if (!audio) { log(id, { type: 'text', text: L(id, '歌詞已存,收到配樂後會自動對時', 'Lyrics saved; they will be timed as soon as the music arrives') }); return Promise.resolve({ ok: true, aligned: false }); }const args = [join(SCRIPTS, 'align_lyrics.py'), audio, join(d, 'inputs', 'lyrics.txt'), '--out', join(out, 'subs.lrc')];- if (m.section?.start_s != null && !/clip/i.test(m.file)) args.push('--start', String(m.section.start_s), '--end', String(m.section.end_s));- log(id, { type: 'tool', name: 'align_lyrics.py', detail: `對時:${m.file}` });+ if (m.section?.start_s != null && !/clip/i.test(song)) args.push('--start', String(m.section.start_s), '--end', String(m.section.end_s));+ log(id, { type: 'tool', name: 'align_lyrics.py', detail: `對時:${song}` });return new Promise((resolve) => {const p = spawn(PY, args, { cwd: ROOT, env: { ...process.env, PYTHONIOENCODING: 'utf-8' } }); let o = '';p.stdout.on('data', (b) => { o += b; }); p.stderr.on('data', () => {});@@ -230,7 +285,8 @@ async function step(id, stageName, phase, vars, must, next, opts) {function collectNeeds(id, items, from) {const add = (items || []).filter(Boolean).map((n) => ({ ...n, from, at: now() }));if (!add.length) return 0;- update(id, (j) => { j.needs = [...(j.needs || []).filter((x) => !add.some((a) => a.issue === x.issue)), ...add]; });+ // a new batch from the same reviewer replaces its earlier one (the critic re-reports open items every round)+ update(id, (j) => { j.needs = [...(j.needs || []).filter((x) => x.from !== from && !add.some((a) => a.issue === x.issue)), ...add]; });chat(id, 'system', L(id, `需要你提供:${add.map((n) => n.issue).join(';')}`, `Needs your input: ${add.map((n) => n.issue).join('; ')}`));return add.length;}@@ -329,6 +385,7 @@ function snapshotEngine(id) {export async function approve(id) {const open = openInputs(id);if (open.length) { const e = new Error('還有需要你提供或略過的素材:' + open.map((r) => r.label || r.id).join('、')); e.code = 409; throw e; }+ await alignIfReady(id).catch(() => null); // lyrics pasted before the music arrived: time them now, before anything is builtupdate(id, (j) => { j.approvedAt = now(); j.approvedPlanVersion = readJSON(join(dirOf(id), 'plan.json'))?.version; j.engineSnapshot = snapshotEngine(id); j.pipeline = {}; j.sessions = j.approvedAtPrev ? {} : Object.fromEntries(Object.entries(j.sessions || {}).filter(([k]) => k.startsWith('cast-'))); j.approvedAtPrev = true; j.needs = []; j.userNote = null; });chat(id, 'system', L(id, `企劃已核准,開始生產:角色關 → 分段製作(每段做完立刻審)→ 組裝 → 最後評審`, 'Plan approved. Production: characters → parts built and reviewed as they finish → assembly → final review'));if (await production(id, { fresh: true })) await finalPanel(id);@@ -349,7 +406,8 @@ async function production(id, { fresh = false } = {}) {const prod = readJSON(join(d, 'build', 'production.json')) || {};const chunks = prod.chunks || [];const old = prev.chunks || {};- pipe(id, (p) => { p.phase = 'shots'; p.chunks = Object.fromEntries(chunks.map((c) => [c.id, old[c.id]?.state === 'passed' ? old[c.id] : { shots: c.shots, state: 'queued', round: 0, fixFirst: !!old[c.id]?.fixFirst }])); });+ // a segment that stopped at its round limit already has a fresh review: resuming fixes those issues first instead of re-reviewing unchanged shots+ pipe(id, (p) => { p.phase = 'shots'; p.chunks = Object.fromEntries(chunks.map((c) => [c.id, old[c.id]?.state === 'passed' ? old[c.id] : { shots: c.shots, state: 'queued', round: 0, fixFirst: !!old[c.id]?.fixFirst || old[c.id]?.state === 'failed' }])); });const runChunk = async (c) => {const key = `builder-${c.id}`, set = (s) => pipe(id, (p) => Object.assign(p.chunks[c.id], s));if (load(id).pipeline.chunks[c.id].state === 'passed') return true;@@ -400,7 +458,7 @@ async function production(id, { fresh = false } = {}) {if (collectNeeds(id, needs, `shot-qa-${c.id}`)) { set({ state: 'needs_user' }); return false; }const bad = c.shots.map((x) => results[x]?.entry).filter((e) => e && !shotPassed(e));if (!bad.length) { set({ state: 'passed' }); return true; }- if (round >= CONFIG.chunkRounds) { set({ state: 'failed', open: bad.length }); return false; }+ if (round >= rounds(id).chunkRounds) { set({ state: 'failed', open: bad.length }); return false; }set({ state: 'fixing' });const f = await turn(id, 'fix_chunk', { chunk: c, bad, round, message: load(id).userNote }, [`out/check/shots/${c.id}.fixes.json`], { session: key, who: key });if (!f.ok) { set({ state: 'error' }); return false; }@@ -453,14 +511,18 @@ async function castGate(id, prev) {chat(id, 'system', L(id, `角色關:${chars.length} 個角色各自由一組審查+修正同時進行`, `Characters: reviewing and fixing ${chars.length} character${chars.length > 1 ? 's' : ''} in parallel`));const shared = [];const one = async (c) => {+ // resuming a character that stopped at its round limit: its last review is still current, so fix those issues first+ const reuse = keep[c.id]?.state === 'failed' && existsSync(join(d, 'out', 'check', 'cast', `review_${c.id}.json`));for (let round = 1; ; round++) {setC(c.id, { state: 'reviewing', round });- const r = await turn(id, 'cast_qa', { round, character: c }, [`out/check/cast/review_${c.id}.json`], { session: 'fresh', who: `cast-qa-${c.id}` });- if (!r.ok) { setC(c.id, { state: 'error' }); return 'error'; }+ if (!(round === 1 && reuse)) {+ const r = await turn(id, 'cast_qa', { round, character: c }, [`out/check/cast/review_${c.id}.json`], { session: 'fresh', who: `cast-qa-${c.id}` });+ if (!r.ok) { setC(c.id, { state: 'error' }); return 'error'; }+ }const rv = readJSON(join(d, 'out', 'check', 'cast', `review_${c.id}.json`)) || {};if (collectNeeds(id, rv.needs_user, `cast-qa-${c.id}`)) { setC(c.id, { state: 'needs_user' }); return 'needs'; }if (passed(rv)) { setC(c.id, { state: 'passed' }); return 'passed'; }- if (round >= CONFIG.castRounds) { setC(c.id, { state: 'failed', issues: (rv.issues || []).length }); return 'failed'; }+ if (round >= rounds(id).castRounds) { setC(c.id, { state: 'failed', issues: (rv.issues || []).length }); return 'failed'; }setC(c.id, { state: 'fixing' });const f = await turn(id, 'cast_fix', { issues: rv.issues || [], round, character: c, rigFiles: prod.rig_files || [] }, [c.sheet, `out/check/cast/fixes_${c.id}.json`], { session: `cast-${c.id}`, who: `cast-${c.id}` });if (!f.ok) { setC(c.id, { state: 'error' }); return 'error'; }@@ -471,7 +533,7 @@ async function castGate(id, prev) {};let res = await Promise.all(chars.map((c) => (keep[c.id]?.state === 'passed' ? 'passed' : one(c))));if (res.includes('needs')) return pause(id);- for (let k = 0; shared.length && k < CONFIG.castRounds; k++) { // skeleton changes: one director turn, then re-check who asked (and anyone it may affect)+ for (let k = 0; shared.length && k < rounds(id).castRounds; k++) { // skeleton changes: one director turn, then re-check who asked (and anyone it may affect)pipe(id, (p) => { p.cast.state = 'fixing'; });const f = await turn(id, 'cast_fix', { issues: [...shared], round: 'shared', shared: true }, ['out/check/cast/sheet.jpg'], { who: 'director' });if (!f.ok) return fail(id, 'producing', f);@@ -479,7 +541,7 @@ async function castGate(id, prev) {res = await Promise.all(chars.map((c, i) => (res[i] === 'passed' || res[i] === 'shared' ? one(c) : res[i])));if (res.includes('needs')) return pause(id);}- if (res.some((x) => x !== 'passed')) { pipe(id, (p) => { p.cast.state = 'failed'; p.cast.round = CONFIG.castRounds; }); chat(id, 'system', L(id, `角色關:${chars.filter((c, i) => res[i] !== 'passed').map((c) => c.name || c.id).join('、')} 審了 ${CONFIG.castRounds} 輪還沒通過,請你看設定圖決定`, `Characters: ${chars.filter((c, i) => res[i] !== 'passed').map((c) => c.name || c.id).join(', ')} still not passing after ${CONFIG.castRounds} rounds. Please check the character sheets and decide`)); setStage(id, 'needs_input'); return false; }+ if (res.some((x) => x !== 'passed')) { pipe(id, (p) => { p.cast.state = 'failed'; p.cast.round = rounds(id).castRounds; }); chat(id, 'system', L(id, `角色關:${chars.filter((c, i) => res[i] !== 'passed').map((c) => c.name || c.id).join('、')} 審了 ${rounds(id).castRounds} 輪還沒通過,請你看設定圖決定`, `Characters: ${chars.filter((c, i) => res[i] !== 'passed').map((c) => c.name || c.id).join(', ')} still not passing after ${rounds(id).castRounds} rounds. Please check the character sheets and decide`)); setStage(id, 'needs_input'); return false; }// every character passed on its own → one line-up check across them, then the serial gate handles anything it findspipe(id, (p) => { p.cast.state = 'reviewing'; p.cast.lineup = true; });const r = await turn(id, 'cast_qa', { round: 'lineup', lineup: true }, ['out/check/cast/review.json'], { session: 'fresh', who: 'cast-qa' });@@ -504,7 +566,7 @@ async function castSerial(id, prev, firstReview) {}if (collectNeeds(id, rv.needs_user, 'cast-qa')) return pause(id);if (passed(rv)) { pipe(id, (p) => { p.cast.pass = true; p.cast.state = 'passed'; }); chat(id, 'system', L(id, `角色關通過(第 ${round} 輪)`, `Characters passed (round ${round})`)); break; }- if (round >= CONFIG.castRounds) { pipe(id, (p) => { p.cast.state = 'failed'; }); chat(id, 'system', L(id, `角色關 ${round} 輪仍未通過,請你看角色設定圖決定`, `Characters still not passing after ${round} rounds. Please check the character sheets and decide`)); setStage(id, 'needs_input'); return false; }+ if (round >= rounds(id).castRounds) { pipe(id, (p) => { p.cast.state = 'failed'; }); chat(id, 'system', L(id, `角色關 ${round} 輪仍未通過,請你看角色設定圖決定`, `Characters still not passing after ${round} rounds. Please check the character sheets and decide`)); setStage(id, 'needs_input'); return false; }pipe(id, (p) => { p.cast.state = 'fixing'; });const f = await turn(id, 'cast_fix', { issues: rv.issues || [], round }, ['out/check/cast/sheet.jpg', 'out/check/cast/fixes.json'], { who: 'director' });if (!f.ok) return fail(id, 'producing', f);@@ -528,7 +590,7 @@ async function finalPanel(id) {update(id, (j) => { j.critiqueRounds = round; j.lastCritique = { pass: !must.length, must: must.length, at: now() }; });const needs = collectNeeds(id, c.needs_user, 'critic');if (!must.length) { chat(id, 'system', needs ? L(id, '評審:導演能修的都過了,剩下需要你提供的項目', 'Final review: everything the director can fix is done. What is left needs your input') : L(id, `評審通過(第 ${round} 輪)`, `Final review passed (round ${round})`)); setStage(id, needs ? 'needs_input' : 'done'); return; }- if (round > CONFIG.finalRounds) { chat(id, 'system', L(id, `評審仍有 ${must.length} 項必修,已達自動修改上限,請你決定`, `The final review still has ${must.length} must-fix item${must.length > 1 ? 's' : ''} and the automatic fix limit is reached. Please decide`)); setStage(id, 'done'); return; }+ if (round > rounds(id).finalRounds) { chat(id, 'system', L(id, `評審仍有 ${must.length} 項必修,已達自動修改上限,請你決定`, `The final review still has ${must.length} must-fix item${must.length > 1 ? 's' : ''} and the automatic fix limit is reached. Please decide`)); setStage(id, 'done'); return; }const msg = must.map((m, i) => `${i + 1}. [${m.shot || '全片'}${m.time != null ? ' ' + m.time + 's' : ''}] ${m.issue}${m.fix ? ' → 建議:' + m.fix : ''}`).join('\n');chat(id, 'system', L(id, `評審第 ${round} 輪:${must.length} 項必修,交回導演(每項要附修改前後對照)`, `Final review round ${round}: ${must.length} must-fix item${must.length > 1 ? 's' : ''}, sent back to the director (each fix needs before/after proof)`));if (!(await step(id, 'revising', 'revise', { message: msg, round }, ['out/video.mp4', 'out/check/fixes.json']))) return;diff --git a/app/web/src/App.jsx b/app/web/src/App.jsxindex e0c13c2..11807d6 100644--- a/app/web/src/App.jsx+++ b/app/web/src/App.jsx@@ -1,6 +1,6 @@import React, { useEffect, useMemo, useRef, useState } from 'react';import { api } from './api.js';-import { I, BrandMark, Orb, Seg, AutoText, ago } from './ui.jsx';+import { I, BrandMark, Orb, Seg, AutoText, ago, RoundsEditor } from './ui.jsx';import { Project, Status } from './Project.jsx';import { LANGS, lang as initialLang, setLang } from './i18n.js';@@ -88,6 +88,9 @@ function Composer({ agents }) {const [file, setFile] = useState(null), [url, setUrl] = useState(''), [linkMode, setLinkMode] = useState(false);const [brief, setBrief] = useState(''), [agent, setAgent] = useState('claude'), [inputs, setInputs] = useState([]);const [drag, setDrag] = useState(false), [busy, setBusy] = useState(false), [err, setErr] = useState('');+ const [rounds, setRounds] = useState({}), [roundsOpen, setRoundsOpen] = useState(false), [defaults, setDefaults] = useState(null);+ useEffect(() => { api.config().then((c) => setDefaults({ castRounds: c.castRounds, chunkRounds: c.chunkRounds, finalRounds: c.finalRounds })).catch(() => {}); }, []);+ const customRounds = Object.entries(rounds).filter(([, v]) => v != null);const pick = useRef(), assets = useRef();const preview = useMemo(() => (file ? URL.createObjectURL(file) : null), [file]);useEffect(() => () => preview && URL.revokeObjectURL(preview), [preview]);@@ -101,6 +104,7 @@ function Composer({ agents }) {if (file) f.append('reference', file); else f.append('url', url.trim());f.append('brief', brief); f.append('agent', agent); f.append('lang', document.documentElement.lang || 'zh-TW');inputs.forEach((x) => f.append('inputs', x));+ customRounds.forEach(([k, v]) => f.append(k, String(v)));try { const { id } = await api.create(f); location.hash = `#/p/${id}`; } catch (e) { setErr(e.message); setBusy(false); }};const yt = ytId(url);@@ -135,6 +139,8 @@ function Composer({ agents }) {<button className={`tool-chip ${inputs.length ? 'on' : ''}`} onClick={() => assets.current.click()} title="配樂、歌詞、圖片、Logo、自家角色設計圖"><I n="clip" />素材{inputs.length > 0 && <span className="n">{inputs.length}</span>}</button><input ref={assets} type="file" multiple hidden onChange={(e) => setInputs([...e.target.files])} />+ {defaults && <button className={`tool-chip ${customRounds.length ? 'on' : ''}`} onClick={() => setRoundsOpen(!roundsOpen)} aria-expanded={roundsOpen} title="每一關最多審查、修改幾輪">+ <I n="sliders" />審查輪數{customRounds.length > 0 && <span className="n">{customRounds.length}</span>}</button>}<span className="grow" /><Seg value={agent} onChange={setAgent} options={[{ value: 'claude', label: <><span className="long">Claude Code</span><span className="short">Claude</span></>, disabled: agents && !agents.claude, title: agents?.claude || '未偵測到' },@@ -142,6 +148,7 @@ function Composer({ agents }) {<button className="send" disabled={!ok} onClick={submit} aria-label="開始">{busy ? <span className="spin-ring" /> : <I n="up" s={2.2} />}</button></div>{inputs.length > 0 && <div className="small faint" style={{ padding: '8px 10px 2px' }}>素材:{inputs.map((f) => f.name).join('、')}</div>}+ {roundsOpen && defaults && <div className="comp-rounds fade-in"><RoundsEditor value={rounds} defaults={defaults} onChange={setRounds} /></div>}</div>{err ? <div className="small" style={{ color: 'var(--red)', textAlign: 'center', marginTop: 12 }}>{err}</div>: <div className="small faint" style={{ textAlign: 'center', marginTop: 12 }}>先拆解與企劃,你核准前不會開始生成 · Ctrl+Enter 送出</div>}diff --git a/app/web/src/Project.jsx b/app/web/src/Project.jsxindex d2a6220..8411031 100644--- a/app/web/src/Project.jsx+++ b/app/web/src/Project.jsx@@ -1,6 +1,6 @@import React, { useEffect, useMemo, useRef, useState } from 'react';import { api } from './api.js';-import { I, Orb, Md, Ring, AutoText, useNow, clock, fmt } from './ui.jsx';+import { I, Orb, Md, Ring, AutoText, useNow, clock, fmt, RoundsEditor } from './ui.jsx';import { Conversation, buildThread, STAGE_DO } from './Chat.jsx';export const STATUS = {@@ -18,6 +18,7 @@ const STEPS = [{ label: '成品', st: ['done', 'revising', 'critiquing'] },];const stepIdx = (job) => { const s = job.stage === 'error' ? job.failed : job.stage; return Math.max(0, STEPS.findIndex((x) => x.st.includes(s))); };+const PRE_PROD = ['planning', 'replanning', 'plan_review']; // required inputs sit at the top of the page in these stagesconst PIPE_DO = { setup: '導演建置角色與共用素材', cast: '角色關:審查角色設定圖', shots: '分段製作,每段做完立刻審查', assemble: '組裝成片', final: '最後評審:接縫、連戲、節奏' };export function Project({ id }) {@@ -37,6 +38,7 @@ export function Project({ id }) {const file = (p) => api.file(id, p, v);const onZoom = (src) => setZoom(src);const P = job.pipeline || {}, chunks = Object.values(P.chunks || {});+ const preProd = PRE_PROD.includes(job.stage) || (job.stage === 'error' && PRE_PROD.includes(job.failed));const tabs = [s.video && { k: 'result', label: '成品', ico: 'play', badge: s.critique && !s.critique.pass ? [`${(s.critique.must_fix || []).length} 項必修`, 'warn'] : null },P.phase && { k: 'pipe', label: '生產線', ico: 'layers', badge: chunks.length ? [`${chunks.filter((c) => c.state === 'passed').length}/${chunks.length}`, ''] : null },@@ -50,7 +52,7 @@ export function Project({ id }) {<a className="back" href="#/"><I n="back" s={2.2} />專案</a><div className="p-head"><div className="grow"><h1>{s.plan?.title || job.title}</h1>{s.plan?.title && <div className="brief-line">{s.plan.logline || s.brief}</div>}</div>- <Status stage={job.stage} />+ <div className="p-head-r">{s.rounds && <RoundsButton id={id} r={s.rounds} />}<Status stage={job.stage} /></div></div><div className="progress">{STEPS.map((x, i) => {@@ -63,6 +65,7 @@ export function Project({ id }) {{working && <LiveBanner id={id} job={job} />}{job.stage === 'error' && <ErrorCard id={id} job={job} />}{(job.stage === 'needs_input' || ((job.needs || []).length > 0 && !working)) && <Needs id={id} s={s} file={file} onZoom={onZoom} />}+ {preProd && (s.requiredInputs || []).length > 0 && <RequiredInputs id={id} s={s} editable top />}{tabs.length > 1 && <div className="tabs" role="tablist">{tabs.map((t) => <button key={t.k} role="tab" aria-selected={cur === t.k} className={cur === t.k ? 'on' : ''} onClick={() => setTab(t.k)}><I n={t.ico} />{t.label}{t.badge && <span className={`tb ${t.badge[1]}`}>{t.badge[0]}</span>}</button>)}</div>}<div key={cur} className="fade-in">{cur === 'result' && <Result s={s} file={file} />}@@ -177,7 +180,8 @@ function Plan({ s, file, job, onTag, onZoom }) {{P.assets.length > 8 && <button className="btn sm plain" style={{ marginTop: 10, marginLeft: -10 }} onClick={() => setAllAssets(!allAssets)}>{allAssets ? '收起' : `顯示全部 ${P.assets.length} 項`}</button>}{s.assetsMd && <details style={{ marginTop: 12 }}><summary className="small muted" style={{ cursor: 'pointer' }}>授權紀錄</summary><div style={{ marginTop: 8 }}><Md src={s.assetsMd} /></div></details>}</section>}- {((s.requiredInputs || []).length > 0 || s.lyrics) && <RequiredInputs id={job.id} s={s} editable={review} />}+ {!PRE_PROD.includes(job.stage) && ((s.requiredInputs || []).length > 0 || s.lyrics) && <RequiredInputs id={job.id} s={s} editable={false} />}+ {PRE_PROD.includes(job.stage) && !(s.requiredInputs || []).length && s.lyrics && <RequiredInputs id={job.id} s={s} editable={review} />}{(P.open_questions || []).length > 0 && <section className="card"><div className="card-h"><h2>需要你決定</h2></div><div className="list">{P.open_questions.map((q, i) => <div key={i} className="li"><div className="li-ico accent"><I n="bubble" /></div><div className="grow">{q}</div>{review && <button className="btn sm plain" onClick={() => onTag({ q })}>回答</button>}</div>)}</div></section>}@@ -223,39 +227,70 @@ function Asset({ a, file }) {}// ---------- required inputs & lyrics ----------+// Things only the user can give (a song, lyrics, their own character art…). Shown at the top of the page while the plan is+// being written or reviewed, so they are found before "approve" is blocked by them.const KIND = { lyrics: '歌詞', audio: '音檔', image: '圖片', text: '文字', other: '檔案' };-function RequiredInputs({ id, s, editable }) {- const req = s.requiredInputs || [];+const ACCEPT = { audio: 'audio/*,video/*,.mp3,.m4a,.wav,.aac,.flac,.ogg', image: 'image/*', lyrics: '.txt,.lrc,text/plain', text: '.txt,.md,text/plain' };+function RequiredInputs({ id, s, editable, top }) {+ const req = s.requiredInputs || [], missing = req.filter((r) => r.status === 'missing');const hasLyrics = req.some((r) => r.kind === 'lyrics') || s.lyrics;+ const [err, setErr] = useState(''), [busy, setBusy] = useState('');+ const act = (k, fn) => async () => { setErr(''); setBusy(k); try { await fn(); } catch (e) { setErr(e.message); } setBusy(''); };return (- <section className="card">- <div className="card-h"><div><h2>需要你提供的素材</h2><div className="small muted" style={{ marginTop: 2 }}>全部提供或略過之後才能核准,生產中不會再卡在這裡。</div></div></div>+ <section id="required-inputs" className={`card req ${top && missing.length ? 'req-top' : ''}`}>+ <div className="card-h"><div>+ <h2>{missing.length ? `需要你提供 ${missing.length} 項素材` : '需要你提供的素材'}</h2>+ <div className="small muted" style={{ marginTop: 2 }}>{missing.length ? '這些只有你能給。提供或略過之後才能核准企劃,生產中不會再卡在這裡。' : '都處理好了。'}</div>+ </div></div>{req.length > 0 && <div className="list">{req.map((r) => (- <div key={r.id} className="li">- <div className={`li-ico ${r.status === 'provided' ? 'ok' : r.status === 'missing' ? 'warn' : ''}`}><I n={r.status === 'provided' ? 'check' : r.status === 'waived' ? 'x' : r.kind === 'lyrics' ? 'music' : 'clip'} s={2} /></div>- <div className="grow"><div className="t">{r.label || r.id}</div><div className="d">{KIND[r.kind] || r.kind}{r.why ? ` · ${r.why}` : ''}</div></div>- {r.status !== 'missing' ? <span className={`cap ${r.status === 'provided' ? 'ok' : ''}`}>{r.status === 'provided' ? '已提供' : '已略過'}</span>- : editable && <div className="row" style={{ gap: 4 }}>{r.kind !== 'lyrics' && <Upload id={id} label="上傳" />}<button className="btn sm plain" onClick={() => api.waive(id, r.id)}>略過</button></div>}+ <div key={r.id} className={`li req-li ${r.status}`}>+ <div className={`li-ico ${r.status === 'provided' ? 'ok' : r.status === 'missing' ? 'warn' : ''}`}><I n={r.status === 'provided' ? 'check' : r.status === 'waived' ? 'x' : r.kind === 'lyrics' || r.kind === 'audio' ? 'music' : r.kind === 'image' ? 'image' : 'clip'} s={2} /></div>+ <div className="grow">+ <div className="t">{r.label || r.id}</div>+ <div className="d">{KIND[r.kind] || r.kind}{r.why ? ` · ${r.why}` : ''}</div>+ {r.files?.length > 0 && <div className="small faint req-files" data-no-i18n>{r.files.map((f) => f.split('/').pop()).join('、')}</div>}+ </div>+ <div className="req-act">+ {r.status === 'provided' && <span className="cap ok"><I n="check" s={2.4} />已提供</span>}+ {r.status === 'waived' && <><span className="cap">已略過</span>{editable && <button className="btn sm plain" disabled={!!busy} onClick={act('u' + r.id, () => api.unwaive(id, r.id))}>復原</button>}</>}+ {editable && r.status !== 'waived' && r.kind !== 'lyrics' && <Upload id={id} forInput={r.id} accept={ACCEPT[r.kind]} multiple={r.kind === 'image' || r.kind === 'other'} label={r.status === 'provided' ? '更換' : `上傳${KIND[r.kind] || '檔案'}`} primary={r.status === 'missing'} />}+ {editable && r.status === 'missing' && r.kind === 'lyrics' && <button className="btn sm primary" onClick={() => { const t = document.getElementById('lyrics-text'); t?.scrollIntoView({ behavior: 'smooth', block: 'center' }); t?.focus({ preventScroll: true }); }}><I n="pencil" />貼上歌詞</button>}+ {editable && r.status !== 'waived' && r.kind === 'lyrics' && <Upload id={id} forInput={r.id} accept={ACCEPT.lyrics} label="上傳 .txt / .lrc" />}+ {editable && r.status === 'missing' && <button className="btn sm plain" disabled={!!busy} onClick={act('w' + r.id, () => api.waive(id, r.id))}>略過</button>}+ </div></div>))}</div>}+ {err && <div className="small" style={{ color: 'var(--red)', marginTop: 8 }}>{err}</div>}{hasLyrics && <Lyrics id={id} s={s} editable={editable || s.job.stage === 'needs_input'} />}</section>);}-export function Upload({ id, label = '上傳檔案' }) {- const [busy, setBusy] = useState(false);- const up = async (files) => { if (!files.length) return; setBusy(true); const f = new FormData(); [...files].forEach((x) => f.append('inputs', x)); try { await api.addInputs(id, f); } finally { setBusy(false); } };- return <label className="btn sm">{busy ? <span className="spin-ring" /> : <I n="clip" />}{busy ? '上傳中' : label}<input type="file" multiple hidden onChange={(e) => up(e.target.files)} /></label>;+export function Upload({ id, label = '上傳檔案', forInput, accept, multiple = true, primary }) {+ const [busy, setBusy] = useState(false), [msg, setMsg] = useState({}), ref = useRef();+ const up = async (files) => {+ if (!files.length) return; setBusy(true); setMsg({});+ const f = new FormData(); [...files].forEach((x) => f.append('inputs', x));+ try { const r = await api.addInputs(id, f, null, forInput); setMsg({ names: (r.saved || []).map((p) => p.split('/').pop()).join('、') }); }+ catch (e) { setMsg({ err: e.message }); } finally { setBusy(false); if (ref.current) ref.current.value = ''; }+ };+ return (+ <span className="upload">+ <label className={`btn sm ${primary ? 'primary' : ''}`}>{busy ? <span className="spin-ring" /> : <I n="clip" />}{busy ? '上傳中' : label}+ <input ref={ref} type="file" multiple={multiple} accept={accept} hidden onChange={(e) => up(e.target.files)} /></label>+ {msg.names && <span className="tiny faint up-msg"><span>已上傳</span> <span data-no-i18n>{msg.names}</span></span>}+ {msg.err && <span className="tiny up-msg" style={{ color: 'var(--red)' }}>{msg.err}</span>}+ </span>+ );}function Lyrics({ id, s, editable }) {const [text, setText] = useState(''), [busy, setBusy] = useState(false), [msg, setMsg] = useState('');const L = s.lyrics?.lines || [];const mean = L.length ? L.reduce((a, l) => a + (l.match || 0), 0) / L.length : 0;- const go = async () => { setBusy(true); setMsg(''); try { const r = await api.lyrics(id, text); setMsg(r.aligned ? '對時完成' : r.ok ? '歌詞已存,配樂確定後會自動對時' : '對時失敗,請看右側紀錄'); if (r.ok) setText(''); } catch (e) { setMsg(e.message); } setBusy(false); };+ const go = async () => { setBusy(true); setMsg(''); try { const r = await api.lyrics(id, text); setMsg(r.aligned ? '對時完成' : r.ok ? '歌詞已存,收到配樂後會自動對時' : '對時失敗,請看右側紀錄'); if (r.ok) setText(''); } catch (e) { setMsg(e.message); } setBusy(false); };return (<div style={{ marginTop: 18 }}><div className="row" style={{ marginBottom: 8 }}><div className="sub-h" style={{ margin: 0 }}>歌詞字幕</div><span className="sp grow" />{L.length > 0 && <span className="cap ok"><I n="check" s={2.4} />{L.length} 句 · 平均匹配 {Math.round(mean * 100)}%</span>}</div>{editable && <>- <textarea className="field-area" placeholder={'貼上歌詞文字,一行一句。\n系統會用你提供的音檔自動對出每一句的時間,不需要自己做 LRC。'} value={text} onChange={(e) => setText(e.target.value)} />+ <textarea id="lyrics-text" className="field-area" placeholder={'貼上歌詞文字,一行一句。\n系統會用你提供的音檔自動對出每一句的時間,不需要自己做 LRC。'} value={text} onChange={(e) => setText(e.target.value)} /><div className="row" style={{ marginTop: 10 }}><button className="btn sm primary" disabled={busy || !text.trim()} onClick={go}>{busy ? <><span className="spin-ring" />對時中,約 1 分鐘</> : <><I n="wand" />{L.length ? '重新對時' : '自動對時'}</>}</button><span className="small muted">{msg}</span></div></>}{L.length > 0 && <div className="list" style={{ marginTop: 12, padding: '2px 4px' }}><table className="lyr"><tbody>{L.map((l, i) => <tr key={i} className={l.match < 0.6 ? 'low' : ''}><td className="tc">{fmt(l.start)} – {fmt(l.end)}</td><td>{l.text}</td><td style={{ whiteSpace: 'nowrap', textAlign: 'right' }} className="small faint"><span className="meter"><i style={{ width: `${Math.round((l.match || 0) * 100)}%` }} /></span>{l.match < 0.6 ? '用前後插值' : `${Math.round(l.match * 100)}%`}</td></tr>)}</tbody></table></div>}@@ -269,6 +304,7 @@ function Approve({ id, open }) {<div className="approve-bar"><div className="grow"><b>{open.length ? `還差 ${open.length} 項素材` : '企劃看起來 OK 嗎?'}</b><div className="small muted">{err || (open.length ? `請先提供或略過:${open.map((r) => r.label || r.id).join('、')}` : '有意見就在右邊說,AI 改完再給你看;核准後才開始生成。')}</div></div>+ {open.length > 0 && <button className="btn" onClick={() => document.getElementById('required-inputs')?.scrollIntoView({ behavior: 'smooth', block: 'start' })}><I n="up" />去提供</button>}<button className="btn primary lg" disabled={open.length > 0 || busy} onClick={go}>{busy ? <span className="spin-ring" /> : <I n="play" />}核准並開始生成</button></div>);@@ -342,11 +378,37 @@ function Needs({ id, s, file, onZoom }) {);}+// ---------- review/fix round limits (header button + panel) ----------+function RoundsButton({ id, r }) {+ const [open, setOpen] = useState(false), [saving, setSaving] = useState(false), [err, setErr] = useState(''), ref = useRef();+ const [local, setLocal] = useState(r.values);+ useEffect(() => { if (!saving) setLocal(r.values); }, [r.values.castRounds, r.values.chunkRounds, r.values.finalRounds]);+ useEffect(() => { if (!open) return; const k = (e) => { if (!ref.current?.contains(e.target)) setOpen(false); }; addEventListener('pointerdown', k); return () => removeEventListener('pointerdown', k); }, [open]);+ const custom = Object.keys(r.defaults).filter((k) => r.values[k] !== r.defaults[k]).length;+ const change = async (next) => {+ const diff = Object.fromEntries(Object.keys(next).filter((k) => next[k] !== local[k]).map((k) => [k, next[k] == null ? '' : next[k]]));+ setLocal({ ...local, ...Object.fromEntries(Object.entries(next).map(([k, v]) => [k, v ?? r.defaults[k]])) });+ setSaving(true); setErr('');+ try { await api.settings(id, diff); } catch (e) { setErr(e.message); setLocal(r.values); } finally { setSaving(false); }+ };+ return (+ <div className="rd-wrap" ref={ref}>+ <button className={`tool-chip ${custom ? 'on' : ''}`} onClick={() => setOpen(!open)} aria-expanded={open} title="每一關最多審查、修改幾輪"><I n="sliders" />審查輪數{custom > 0 && <span className="n">{custom}</span>}</button>+ {open && <div className="rd-pop">+ <div className="row" style={{ marginBottom: 4 }}><b style={{ fontSize: 15 }}>審查輪數</b><span className="grow" />{saving ? <span className="spin-ring" style={{ width: 12, height: 12 }} /> : <span className="tiny faint">已自動儲存</span>}</div>+ <div className="tiny muted" style={{ marginBottom: 6 }}>做到一半也可以改,從下一次檢查開始生效。</div>+ <RoundsEditor value={Object.fromEntries(Object.entries(local).map(([k, v]) => [k, v === r.defaults[k] ? null : v]))} defaults={r.defaults} min={r.min} max={r.max} onChange={change} />+ {err && <div className="small" style={{ color: 'var(--red)', marginTop: 6 }}>{err}</div>}+ </div>}+ </div>+ );+}+// ---------- production line ----------const CHUNK = { queued: ['排隊中', ''], building: ['製作中', 'live'], reviewing: ['審查中', 'live'], fixing: ['修正中', 'warn'], passed: ['通過', 'ok'], failed: ['未通過', 'bad'], error: ['錯誤', 'bad'], needs_user: ['等你提供', 'warn'], shared_fix: ['導演改共用檔', 'live'], waiting_cast: ['做好了,等角色關', ''], built: ['做好了,等角色關', ''] };const PHASES = [['setup', '建置', 'layers'], ['cast', '角色關', 'user'], ['shots', '分段製作', 'film'], ['assemble', '組裝', 'play'], ['final', '最後評審', 'mag']];function Pipeline({ s, file, onZoom }) {- const p = s.job.pipeline || {}, rv = s.cast?.review, chunks = Object.entries(p.chunks || {});+ const p = s.job.pipeline || {}, rv = s.cast?.review, chunks = Object.entries(p.chunks || {}), R = s.rounds?.values || {};const cur = PHASES.findIndex(([k]) => k === p.phase), allDone = s.job.stage === 'done';const passed = chunks.filter(([, v]) => v.state === 'passed').length;return (@@ -359,9 +421,9 @@ function Pipeline({ s, file, onZoom }) {{(s.cast?.sheets || []).length > 0 && <><div className="row" style={{ marginTop: 22, marginBottom: 10 }}><div className="sub-h" style={{ margin: 0 }}>角色設定圖</div><span className="grow" />- {p.cast?.state && <span className={`cap ${p.cast.pass ? 'ok' : p.cast.state === 'failed' ? 'bad' : p.cast.state === 'fixing' ? 'warn' : 'live'}`}>{p.cast.pass ? <><I n="check" s={2.4} />已通過</> : { reviewing: '審查中', fixing: '導演修正中', failed: '未通過' }[p.cast.state] || p.cast.state}{p.cast.round > 1 ? ` · 第 ${p.cast.round} 輪` : ''}</span>}</div>+ {p.cast?.state && <span className={`cap ${p.cast.pass ? 'ok' : p.cast.state === 'failed' ? 'bad' : p.cast.state === 'fixing' ? 'warn' : 'live'}`}>{p.cast.pass ? <><I n="check" s={2.4} />已通過</> : { reviewing: '審查中', fixing: '導演修正中', failed: '未通過' }[p.cast.state] || p.cast.state}{p.cast.round > 1 ? ` · 第 ${p.cast.round} / ${R.castRounds} 輪` : ''}</span>}</div><div className="scroller">{(s.cast.sheets.filter((f) => /sheet/i.test(f.split('/').pop())).length ? s.cast.sheets.filter((f) => /sheet/i.test(f.split('/').pop())) : s.cast.sheets).map((f) => <img key={f} className="shot-img" src={file(f)} onClick={() => onZoom(file(f))} />)}</div>- {p.cast?.chars && <div className="chunks" style={{ marginTop: 12 }}>{Object.entries(p.cast.chars).map(([k, c]) => { const [t, cl] = CHUNK[c.state] || (c.state === 'waiting_shared' ? ['等導演改骨架', 'warn'] : [c.state, '']); return <div key={k} className={`chunk ${c.state}`}><div className="ch-h"><b style={{ fontSize: 15 }}>{(s.production?.characters || []).find((x) => x.id === k)?.name || k}</b><span className="grow" /><span className={`cap ${cl}`} style={{ height: 22, fontSize: 11.5 }}>{cl === 'live' && <span className="dot live" />}{t}</span></div>{c.round > 1 && <div className="tiny faint">第 {c.round} 輪</div>}</div>; })}</div>}+ {p.cast?.chars && <div className="chunks" style={{ marginTop: 12 }}>{Object.entries(p.cast.chars).map(([k, c]) => { const [t, cl] = CHUNK[c.state] || (c.state === 'waiting_shared' ? ['等導演改骨架', 'warn'] : [c.state, '']); return <div key={k} className={`chunk ${c.state}`}><div className="ch-h"><b style={{ fontSize: 15 }}>{(s.production?.characters || []).find((x) => x.id === k)?.name || k}</b><span className="grow" /><span className={`cap ${cl}`} style={{ height: 22, fontSize: 11.5 }}>{cl === 'live' && <span className="dot live" />}{t}</span></div>{c.round > 1 && <div className="tiny faint">第 {c.round} / {R.castRounds} 輪</div>}</div>; })}</div>}{rv && !rv.pass && (rv.issues || []).length > 0 && <ul className="issues" onClick={(e) => e.target.closest('li')?.classList.toggle('open')}>{rv.issues.map((x, i) => <li key={i}><span className="tagc">{x.character || '角色'}</span><span>{x.what && <b>{x.what}:</b>}{x.issue}{x.fix && <span className="faint"> → {x.fix}</span>}</span></li>)}</ul>}</>}@@ -371,7 +433,7 @@ function Pipeline({ s, file, onZoom }) {<div key={k} className={`chunk ${v.state}`}><div className="ch-h"><b>{k}</b><span className="grow" /><span className={`cap ${c}`} style={{ height: 22, fontSize: 11.5 }}>{c === 'live' && <span className="dot live" />}{t}</span></div><div className="small muted">{(v.shots || []).join(' · ')}</div>- {v.round > 1 && <div className="tiny faint">第 {v.round} 輪審查</div>}+ {v.round > 1 && <div className="tiny faint">第 {v.round} / {R.chunkRounds} 輪審查</div>}</div>); })}</div></>}diff --git a/app/web/src/api.js b/app/web/src/api.jsindex 4ddd86d..606c070 100644--- a/app/web/src/api.js+++ b/app/web/src/api.js@@ -5,12 +5,15 @@ export const api = {projects: () => fetch('/api/projects').then(j),project: (id) => fetch(`/api/projects/${id}`).then(j),create: (form) => fetch('/api/projects', { method: 'POST', body: form }).then(j),- addInputs: (id, form, to) => fetch(`/api/projects/${id}/inputs${to ? `?to=${to}` : ''}`, { method: 'POST', body: form }).then(j),+ addInputs: (id, form, to, forInput) => fetch(`/api/projects/${id}/inputs?${new URLSearchParams({ ...(to ? { to } : {}), ...(forInput ? { for: forInput } : {}) })}`, { method: 'POST', body: form }).then(j),message: (id, text, meta) => fetch(`/api/projects/${id}/message`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text, meta }) }).then(j),approve: (id) => fetch(`/api/projects/${id}/approve`, { method: 'POST' }).then(j),retry: (id) => fetch(`/api/projects/${id}/retry`, { method: 'POST' }).then(j),lyrics: (id, text) => fetch(`/api/projects/${id}/lyrics`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text }) }).then(j),+ unwaive: (id, input) => fetch(`/api/projects/${id}/unwaive`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ input }) }).then(j),waive: (id, input) => fetch(`/api/projects/${id}/waive`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ input }) }).then(j),+ config: () => fetch('/api/config').then(j),+ settings: (id, body) => fetch(`/api/projects/${id}/settings`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then(j),accept: (id) => fetch(`/api/projects/${id}/accept`, { method: 'POST' }).then(j),resume: (id) => fetch(`/api/projects/${id}/resume`, { method: 'POST' }).then(j),cancel: (id) => fetch(`/api/projects/${id}/cancel`, { method: 'POST' }).then(j),diff --git a/app/web/src/i18n.js b/app/web/src/i18n.jsindex 882ea87..9eecc69 100644--- a/app/web/src/i18n.js+++ b/app/web/src/i18n.js@@ -89,7 +89,7 @@ const EN = {'對企劃提意見,例如:S3 的轉場想更誇張…': 'Comment on the plan, e.g. make the S3 transition bigger…','對成片提意見,例如:12 秒那裡太快看不懂…': 'Comment on the film, e.g. too fast to follow at 12 s…','告訴導演怎麼處理,或補充說明…': 'Tell the director what to do, or add details…', '說明要怎麼處理這個問題…': 'Explain how to handle this…',- '企劃還在寫,可以先補充想法,導演會一併放進企劃…': 'The plan is still being written — add ideas now and the director will fold them in…', '網站已更新,點這裡重新整理': 'ReelMimic was updated — click to refresh', '請上傳參考影片或貼上影片連結': 'Upload a reference video or paste a link', 'agent 正在工作中,請等這一輪完成': 'The agent is working — wait for this turn to finish', '請貼上歌詞文字': 'Paste the lyrics text', '需求文字編碼錯誤(請用 UTF-8 送出)': 'The text encoding is wrong (send it as UTF-8)', 'AI 帳號的用量到上限了': 'Your AI account hit its usage limit', '等額度恢復,或換另一個 AI 導演,再從這裡繼續;做到一半的檔案都還在。': 'Wait until it resets, or switch to the other AI director, then continue from here. Work in progress is kept.', 'AI 工作中,這一輪完成後就可以說話': 'The AI is working — you can talk once this turn finishes',+ '企劃還在寫,可以先補充想法,導演會一併放進企劃…': 'The plan is still being written — add ideas now and the director will fold them in…', '網站已更新,點這裡重新整理': 'ReelMimic was updated — click to refresh', '請上傳參考影片或貼上影片連結': 'Upload a reference video or paste a link', 'agent 正在工作中,請等這一輪完成': 'The agent is working — wait for this turn to finish', '請貼上歌詞文字': 'Paste the lyrics text', '需求文字編碼錯誤(請用 UTF-8 送出)': 'The text encoding is wrong (send it as UTF-8)', 'AI 帳號的用量到上限了': 'Your AI account hit its usage limit', '等額度恢復,或換另一個 AI 導演,再從這裡繼續;做到一半的檔案都還在。': 'Wait until it resets, or switch to the other AI director, then continue from here. Work in progress is kept.', '審查輪數': 'Review rounds', '每一關最多審查、修改幾輪': 'How many review/fix rounds each step may take', '每段鏡頭': 'Each part', '每個角色最多審幾輪': 'Max rounds per character', '每段最多審幾輪': 'Max rounds per part', '自動修改最多幾輪': 'Max automatic revision rounds', '· 預設': '· default', '已自動儲存': 'Saved', '做到一半也可以改,從下一次檢查開始生效。': 'You can change this mid-production; it applies from the next check.', '到了上限還沒通過,會暫停請你決定,不會一直來回修改。輪數多,品質有機會更好,但時間和 AI 用量也會增加。': 'When a limit is reached, the job pauses and asks you instead of looping. More rounds can mean better quality, but also more time and AI usage.', '減少': 'Decrease', '增加': 'Increase', '這些只有你能給。提供或略過之後才能核准企劃,生產中不會再卡在這裡。': 'Only you can provide these. Add or skip them to approve the plan; production won’t stop for them later.', '都處理好了。': 'All set.', '復原': 'Undo', '更換': 'Replace', '上傳音檔': 'Upload audio', '上傳圖片': 'Upload image', '上傳文字': 'Upload text', '上傳 .txt / .lrc': 'Upload .txt / .lrc', '已上傳': 'Uploaded', '去提供': 'Go provide', '歌詞已存,收到配樂後會自動對時': 'Lyrics saved; they will be timed as soon as the music arrives', '恢復預設': 'Reset to defaults', '貼上歌詞': 'Paste lyrics', 'AI 工作中,這一輪完成後就可以說話': 'The AI is working — you can talk once this turn finishes','Enter 送出 · Shift+Enter 換行 · 圖片可以直接貼上或拖進來': 'Enter to send · Shift+Enter for a new line · paste or drop images','附加檔案': 'Attach files', '附加圖片或檔案(也可以直接貼上或拖進來)': 'Attach images or files (you can also paste or drop them)', '送出': 'Send','全部 agent': 'All agents', '搜尋紀錄': 'Search log', '下載紀錄': 'Download log', '沒有紀錄': 'No log entries', '完整紀錄在': 'full log in',@@ -124,6 +124,8 @@ const EN_RE = [[/^AI 這一輪結束了,但沒有產出應有的檔案((.+))。通常再跑一次就會好;也可以在右邊說明要怎麼處理。$/, 'The AI finished its turn but did not produce $1. Running it again usually works; or explain on the right how to handle it.'],[/^前製企劃 · v$/, 'Pre-production · v'], [/^(\d+) 句 · 平均匹配 (\d+)%$/, '$1 lines · avg match $2%'],[/^還有需要你提供或略過的素材:(.+)$/, 'Still needs your input or a skip: $1'],+ [/^· 預設 (\d+)$/, '· default $1'], [/^· 第 (\d+) \/ (\d+) 輪$/, '· round $1 / $2'],+ [/^需要你提供 (\d+) 項素材$/, 'Needs $1 input(s) from you'],[/^速度 (.+)$/, 'pace $1'], [/^主體 (.+)$/, 'subject $1'], [/^進:(.+)$/, 'in: $1'], [/^出:(.+)$/, 'out: $1'], [/^評審:(.+)$/, 'Critic: $1'],];diff --git a/app/web/src/styles.css b/app/web/src/styles.cssindex 0cec948..4989a59 100644--- a/app/web/src/styles.css+++ b/app/web/src/styles.css@@ -612,3 +612,34 @@ h1, h2, h3 { font-family: var(--font-display); margin: 0; letter-spacing: -.022eborder: 0; border-radius: 999px; padding: 10px 18px; font: inherit; font-size: 13.5px; font-weight: 600; cursor: pointer;background: var(--accent); color: #fff; box-shadow: var(--shadow-3); animation: fade .3s var(--ease) both; }.update-pill:hover { background: color-mix(in srgb, var(--accent) 88%, #000); }++/* review/fix round limits: header button + popover, composer panel */+.p-head-r { display: flex; align-items: center; gap: 8px; }+.rd-wrap { position: relative; }+.rd-pop { position: absolute; right: 0; top: 42px; z-index: 30; width: min(340px, calc(100vw - 32px)); padding: 14px 16px 12px; border-radius: 16px; background: var(--elevated); backdrop-filter: saturate(180%) blur(24px); -webkit-backdrop-filter: saturate(180%) blur(24px); box-shadow: var(--shadow-3); animation: pop .3s var(--spring) both; transform-origin: top right; }+.rounds { display: grid; gap: 2px; }+.rd-row { display: flex; align-items: center; gap: 12px; padding: 8px 0; border-bottom: 1px solid var(--sep); }+.rd-row b { font-size: 14px; font-weight: 600; }+.stepper { display: inline-flex; align-items: center; gap: 2px; padding: 2px; border-radius: 99px; background: var(--fill-2); }+.stepper .icon-btn { width: 30px; height: 30px; font-size: 15px; }+.stepper .icon-btn:hover:not(:disabled) { background: var(--fill); color: var(--label); }+.stepper .icon-btn:disabled { opacity: .3; cursor: default; }+.stepper .num { min-width: 26px; text-align: center; font-size: 15px; font-weight: 650; font-variant-numeric: tabular-nums; }+.stepper .num.custom { color: var(--accent-ink); }+.rd-note { padding-top: 8px; line-height: 1.5; }+.comp-rounds { margin: 10px 6px 4px; padding: 6px 14px 10px; border-radius: 14px; background: var(--fill-2); }+.comp-rounds .rd-row:last-of-type { border-bottom: 0; }++/* required inputs: at the top of the page while the plan is being written / reviewed */+.card.req-top { box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--orange, #FF9F0A) 55%, transparent), var(--shadow-2); }+.req-li { flex-wrap: wrap; row-gap: 8px; }+.req-li.waived .t { color: var(--label-3); text-decoration: line-through; }+.req-act { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; justify-content: flex-end; }+.req-files { margin-top: 3px; word-break: break-all; }+.upload { display: inline-flex; align-items: center; gap: 8px; flex-wrap: wrap; }+.upload label.btn { cursor: pointer; }+.up-msg { max-width: 260px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+@media (max-width: 640px) { .req-act { width: 100%; justify-content: flex-start; padding-left: 46px; } }+.rd-foot { display: flex; align-items: flex-end; gap: 10px; }+.rd-foot .rd-note { flex: 1; }+.rd-foot .btn { flex: none; }diff --git a/app/web/src/ui.jsx b/app/web/src/ui.jsxindex 35795e1..7065440 100644--- a/app/web/src/ui.jsx+++ b/app/web/src/ui.jsx@@ -3,6 +3,8 @@ import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 're// ---------- icons (SF-Symbols-like strokes) ----------const P = {plus: 'M12 5v14M5 12h14',+ minus: 'M5 12h14',+ sliders: 'M4 7h9M17 7h3M15 4.5v5M4 17h3M11 17h9M9 14.5v5',link: 'M10 14a4.5 4.5 0 0 0 6.4 0l3-3a4.5 4.5 0 0 0-6.4-6.4l-1 1M14 10a4.5 4.5 0 0 0-6.4 0l-3 3a4.5 4.5 0 0 0 6.4 6.4l1-1',clip: 'M20 11.5 12.3 19.2a5 5 0 0 1-7.1-7.1l8.1-8.1a3.3 3.3 0 0 1 4.7 4.7l-8.1 8.1a1.7 1.7 0 0 1-2.4-2.4l7.4-7.4',up: 'M12 19V5M5.5 11.5 12 5l6.5 6.5',@@ -129,3 +131,36 @@ export const AutoText = React.forwardRef(function AutoText({ value, onChange, miuseLayoutEffect(() => { const t = ref.current; if (!t) return; t.style.height = 'auto'; t.style.height = t.scrollHeight + 'px'; }, [value]);return <textarea ref={ref} rows={minRows} value={value} onChange={onChange} {...rest} />;});++// ---------- review/fix round limits (per project) ----------+// value: the project's own settings (may be partial); defaults: server defaults. Changing a number calls onChange with+// the full next value; a number equal to its default is sent as null (= follow the default).+export const ROUND_FIELDS = [+ ['castRounds', '角色關', '每個角色最多審幾輪'],+ ['chunkRounds', '每段鏡頭', '每段最多審幾輪'],+ ['finalRounds', '最後評審', '自動修改最多幾輪'],+];+export function RoundsEditor({ value = {}, defaults = {}, min = 1, max = 10, onChange, disabled }) {+ const set = (k, v) => onChange({ ...value, [k]: v === defaults[k] ? null : v });+ return (+ <div className="rounds">+ {ROUND_FIELDS.map(([k, label, hint]) => {+ const v = value[k] ?? defaults[k], custom = value[k] != null && value[k] !== defaults[k];+ return (+ <div className="rd-row" key={k}>+ <div className="grow"><b>{label}</b><div className="tiny faint">{hint}{custom ? ` · 預設 ${defaults[k]}` : ' · 預設'}</div></div>+ <div className="stepper">+ <button className="icon-btn" disabled={disabled || v <= min} onClick={() => set(k, v - 1)} aria-label="減少"><I n="minus" /></button>+ <span className={`num ${custom ? 'custom' : ''}`}>{v}</span>+ <button className="icon-btn" disabled={disabled || v >= max} onClick={() => set(k, v + 1)} aria-label="增加"><I n="plus" /></button>+ </div>+ </div>+ );+ })}+ <div className="rd-foot">+ <div className="tiny faint rd-note">到了上限還沒通過,會暫停請你決定,不會一直來回修改。輪數多,品質有機會更好,但時間和 AI 用量也會增加。</div>+ {ROUND_FIELDS.some(([k]) => value[k] != null && value[k] !== defaults[k]) && <button className="btn sm plain" disabled={disabled} onClick={() => onChange(Object.fromEntries(ROUND_FIELDS.map(([k]) => [k, null])))}>恢復預設</button>}+ </div>+ </div>+ );+}