Skip to content

Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.

25.4 KB
Raw Blame
// Server API + UI. Chỉ bind 127.0.0.1:4400. Không framework.
import http from 'node:http';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { spawn } from 'node:child_process';
import {
  ROOT, JOBS, TEMPLATES, loadCatalog, templateName, createJob, runJob, renderJob, readJob, listJobs, readLog, markStale,
  dueJobs, resolveMode, submitScene, previewJob, createJobs, MAX_BATCH,
} from '../generator/jobs.mjs';
import { findClaude } from '../generator/claude.mjs';
import { rewriteScript, resolveRewriteEngine, REWRITE_MAX_CHARS } from '../generator/rewrite.mjs';
import { config } from '../generator/config.mjs';
import { reAudio, listVersions, audioBusy, saveAudioSpec } from '../generator/audio-job.mjs';
import { audioOptions, normalizeAudioPrefs, voiceEngine, sampleTextFor } from '../engine/audio/prefs.mjs';
import { MUSIC_STYLES, writeMusic } from '../engine/audio/music.mjs';
import { synthVoice } from '../engine/audio/voice.mjs';
import { handleEditRoute, initEdits } from '../edit/http.mjs';
import { handleVoiceRoute, initVoices } from './voices-http.mjs';
import { handlePackRoute } from '../packs/http.mjs';
import { listTemplates, resolveTemplate, parsePackRef, BUILTIN_TEMPLATE_RE } from '../packs/registry.mjs';
import { originOk } from '../edit/http.mjs';
import { isCloneVoice, cloneRef } from '../engine/audio/voice-store.mjs';
import { handleDraftRoute, initDrafts } from '../packs/drafts-http.mjs';
import { handleLogRoute, installLogCapture, redact } from './logs.mjs';
import { readEditJob, EDITS } from '../edit/jobs.mjs';
import { handleDoctorRoute } from './doctor.mjs';

installLogCapture(ROOT); // log server vào ring buffer (GET /api/logs/server)

const AUDIO_SAMPLES = path.join(ROOT, 'engine', 'audio', 'samples');
/** File nghe thử (cache trong engine/audio/samples/, chỉ sinh khi chưa có). Trả đường dẫn tuyệt đối. */
async function audioPreviewFile(q) {
  const style = q.get('style'), voice = q.get('voice');
  if (style) {
    if (!MUSIC_STYLES.includes(style)) throw new Error('style nhạc không có: ' + style);
    const f = path.join(AUDIO_SAMPLES, `music-${style}.wav`);
    if (!fs.existsSync(f)) { fs.mkdirSync(AUDIO_SAMPLES, { recursive: true }); writeMusic(style, f, 8, 1); }
    return f;
  }
  if (voice) {
    const { voice: v } = normalizeAudioPrefs({ voice });
    const text = String(q.get('text') || sampleTextFor(v)).trim().slice(0, 160);
    if (v === 'auto' || v === 'none') throw new Error('chọn 1 giọng cụ thể để nghe thử');
    // giọng nhân bản: câu nghe thử đã đọc sẵn lúc tạo giọng
    if (isCloneVoice(v) && !q.get('text')) { const f = path.join(path.dirname(cloneRef(v).wav), 'sample.wav'); if (fs.existsSync(f)) return f; }
    const ve = voiceEngine(v);
    const [r] = await synthVoice([{ t: 0, text }], path.join(AUDIO_SAMPLES, 'voices'), { engine: ve.engine, voice: ve.speaker, log: (l) => console.log('[audio] ' + l) });
    return r.file;
  }
  throw new Error('cần ?style=<nhạc> hoặc ?voice=<giọng>&text=...');
}

const HOST = '127.0.0.1';
const PORT = Number(process.env.PORT) || 4400;
const PUBLIC = path.join(path.dirname(fileURLToPath(import.meta.url)), 'public');
const DEFAULT_MODE = process.env.VIDEOAI_MODE || 'auto';
const ALLOWED_HOSTS = new Set([`127.0.0.1:${PORT}`, `localhost:${PORT}`]);
// L9: trang chỉ chạy script của chính app (file ngoài, index.html không có script nội tuyến); chữ của gói không thành code được.
const PAGE_CSP = "default-src 'self'; img-src 'self' data: blob:; media-src 'self' blob:; style-src 'self' 'unsafe-inline'; object-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'";

const FRAME_CSP = "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; font-src 'self'; connect-src 'none'; object-src 'none'; frame-ancestors 'self'; base-uri 'none'; form-action 'none'";

const MIME = {
  '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
  '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
  '.png': 'image/png', '.webp': 'image/webp', '.svg': 'image/svg+xml', '.mp4': 'video/mp4', '.m4a': 'audio/mp4', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.aac': 'audio/aac', '.ogg': 'audio/ogg', '.opus': 'audio/ogg', '.flac': 'audio/flac', '.woff2': 'font/woff2', '.md': 'text/markdown; charset=utf-8',
};

// ---- hàng đợi: mỗi lúc chỉ 1 job chạy (render nặng) ----
const queue = [];
let busy = false;
const queuedIds = new Set();
/** Xếp 1 job vào hàng (không xếp trùng). */
function enqueueJob(id, fn) {
  if (queuedIds.has(id)) return;
  queuedIds.add(id);
  enqueue(async () => { try { await fn(); } finally { queuedIds.delete(id); } });
}
function enqueue(fn) {
  queue.push(fn);
  pump();
}
async function pump() {
  if (busy) return;
  const fn = queue.shift();
  if (!fn) return;
  busy = true;
  try { await fn(); } catch (e) { console.error('[queue]', e); }
  busy = false;
  pump();
}

function send(res, code, body, type = 'application/json; charset=utf-8') {
  const data = typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body);
  res.writeHead(code, { 'Content-Type': type, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
  res.end(data);
}

/** Phục vụ file tĩnh trong baseDir (chặn ../), hỗ trợ Range cho video. */
function serveFile(req, res, baseDir, rel) {
  const file = path.resolve(baseDir, '.' + path.sep + rel);
  if (!file.startsWith(path.resolve(baseDir) + path.sep)) return send(res, 403, { error: 'forbidden' });
  let st;
  try { st = fs.statSync(file); } catch { return send(res, 404, { error: 'không thấy file' }); }
  if (!st.isFile()) return send(res, 404, { error: 'không thấy file' });
  const type = MIME[path.extname(file).toLowerCase()] || 'application/octet-stream';
  const range = req.headers.range && /bytes=(\d*)-(\d*)/.exec(req.headers.range);
  const headers = { 'Content-Type': type, 'Accept-Ranges': 'bytes', 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' };
  // khung xem trước đồ hoạ của Studio (studio/gfx-frame.html) được nhúng vào chính trang app (iframe sandbox): frame-ancestors 'self'
  if (type.startsWith('text/html')) headers['Content-Security-Policy'] = path.basename(file) === 'gfx-frame.html' ? FRAME_CSP : PAGE_CSP;
  if (range) {
    const start = range[1] ? Number(range[1]) : 0;
    const end = range[2] ? Math.min(Number(range[2]), st.size - 1) : st.size - 1;
    if (start >= st.size || start > end) { res.writeHead(416, { 'Content-Range': `bytes */${st.size}` }); return res.end(); }
    res.writeHead(206, { ...headers, 'Content-Range': `bytes ${start}-${end}/${st.size}`, 'Content-Length': end - start + 1 });
    return fs.createReadStream(file, { start, end }).pipe(res);
  }
  res.writeHead(200, { ...headers, 'Content-Length': st.size });
  if (req.method === 'HEAD') return res.end();
  fs.createReadStream(file).pipe(res);
}

function readBody(req, limit = 64 * 1024) {
  return new Promise((resolve, reject) => {
    let size = 0; const chunks = [];
    req.on('data', (c) => { size += c.length; if (size > limit) { reject(new Error('body quá lớn')); req.destroy(); } else chunks.push(c); });
    req.on('end', () => {
      try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')); } catch { reject(new Error('JSON không hợp lệ')); }
    });
    req.on('error', reject);
  });
}

// Ảnh/video minh hoạ mỗi mẫu, theo thứ tự ưu tiên:
//  ảnh: 1. site/dist/media/<id>.webp (poster video demo, sinh bởi site/build.mjs — không có trong repo)
//        2. templates/thumbs/<id>.webp (khung keyframe 360×640 có sẵn trong repo; tạo bằng scripts/make-thumbs.mjs)
//        3. khung video tham chiếu riêng trên máy (templates/ref/<id>/frames, tools/fetch_refs.py — không có trong repo)
//        4. poster SVG tự dựng (/poster/<id>.svg) từ tên + nhóm của mẫu
//  video: demo (site/dist/media/<id>.mp4) → video tham chiếu riêng → không có
const DEMO = path.join(ROOT, 'site', 'dist', 'media');
const THUMBS = path.join(TEMPLATES, 'thumbs');
// LUMREELS_NO_REF=1: bỏ qua templates/ref (giả lập máy vừa clone repo; dùng khi chụp ảnh docs).
const USE_REF = process.env.LUMREELS_NO_REF !== '1';
function templateList() {
  // gốc + gói (packs/registry.mjs). Mẫu gói: ảnh từ gói (/pack-thumbs/…) hoặc poster SVG; không có video demo.
  return listTemplates().map((t) => {
    if (t.source !== 'builtin') {
      const pr = parsePackRef(t.ref);
      const r = resolveTemplate(t.ref);
      return {
        id: t.ref, ref: t.ref, name: t.name, blurb: t.blurb || '', category: t.category, genre: t.genre || '', technique: t.technique || [],
        difficulty: t.difficulty, narration: !!t.narration, source: t.source, packId: t.packId, restricted: true, hasGuidance: true,
        thumb: r?.thumbFile ? `/pack-thumbs/${pr.packId}/template-${pr.slug}.webp` : `/poster/p/${pr.packId}/${pr.slug}.svg`,
        video: null, videoKind: null,
      };
    }
    const ref = path.join(TEMPLATES, 'ref', t.id);
    const refThumb = USE_REF && ['f_08.jpg', 'f_09.jpg', 'f_07.jpg'].find((f) => fs.existsSync(path.join(ref, 'frames', f)));
    const demo = fs.existsSync(path.join(DEMO, `${t.id}.mp4`));
    const demoPoster = fs.existsSync(path.join(DEMO, `${t.id}.webp`));
    const keyThumb = fs.existsSync(path.join(THUMBS, `${t.id}.webp`));
    const refVideo = USE_REF && fs.existsSync(path.join(ref, 'video.mp4'));
    return {
      id: t.id, ref: t.id, name: t.name, blurb: t.blurb || '', category: t.category, genre: t.genre, technique: t.technique,
      difficulty: t.difficulty, narration: t.narration, source: 'builtin', restricted: t.restricted,
      hasGuidance: t.hasGuidance,
      thumb: demoPoster ? `/demo/${t.id}.webp` : keyThumb ? `/thumbs/${t.id}.webp` : refThumb ? `/ref/${t.id}/frames/${refThumb}` : `/poster/${t.id}.svg`,
      video: demo ? `/demo/${t.id}.mp4` : refVideo ? `/ref/${t.id}/video.mp4` : null,
      videoKind: demo ? 'demo' : refVideo ? 'ref' : null,
      source: 'builtin',
    };
  });
}

/** Poster SVG cho mẫu chưa có video demo: nền gradient theo id, tên phong cách, nhóm. */
const CAT_LABEL = { faceless: 'Faceless', ads: 'Quảng cáo', 'multi-style': 'Đa phong cách', 'viet-nam': 'Việt Nam hoá' };
function posterSvg(t) {
  const n = BUILTIN_TEMPLATE_RE.test(t.id) ? Number(t.id) : [...String(t.id)].reduce((a, c) => (a * 31 + c.charCodeAt(0)) % 997, 7);
  const h1 = (n * 47) % 360, h2 = (h1 + 40 + (n % 5) * 12) % 360;
  const x = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
  // ngắt tên thành tối đa 4 dòng ~12 ký tự
  const words = String(t.name).split(/\s+/); const lines = [''];
  for (const w of words) { if ((lines.at(-1) + ' ' + w).trim().length > 12 && lines.at(-1)) lines.push(w); else lines[lines.length - 1] = (lines.at(-1) + ' ' + w).trim(); }
  const shown = lines.slice(0, 4);
  const tech = (t.technique || []).includes('three') ? '3D' : (t.technique || []).includes('webgl-shader') ? 'Shader' : '2D';
  return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 540 960" width="540" height="960">
<defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="hsl(${h1} 45% 22%)"/><stop offset="1" stop-color="hsl(${h2} 55% 12%)"/></linearGradient></defs>
<rect width="540" height="960" fill="url(#g)"/>
<circle cx="${380 + (n % 7) * 10}" cy="${260 + (n % 4) * 30}" r="170" fill="hsl(${h2} 70% 60% / .18)"/>
<rect x="44" y="300" width="72" height="8" rx="4" fill="hsl(${h1} 80% 70%)"/>
<text x="44" y="270" font-family="'Be Vietnam Pro',sans-serif" font-size="30" font-weight="600" fill="#fff" fill-opacity=".7">${BUILTIN_TEMPLATE_RE.test(t.id) ? '#' + x(t.id) : x(String(t.id).split('/')[1] || '')}</text>
${shown.map((l, i) => `<text x="44" y="${390 + i * 74}" font-family="'Be Vietnam Pro',sans-serif" font-size="60" font-weight="800" fill="#fff">${x(l)}</text>`).join('\n')}
<text x="44" y="880" font-family="'Be Vietnam Pro',sans-serif" font-size="28" font-weight="500" fill="#fff" fill-opacity=".75">${x(CAT_LABEL[t.category] || t.category)} · ${tech}</text>
</svg>`;
}

function jobView(job, withLog = false) {
  const dir = path.join(JOBS, job.id);
  const has = (f) => fs.existsSync(path.join(dir, f));
  const v = {
    ...job,
    templateTitle: templateName(job.templateId) || job.templateTitle,
    queued: queue.length,
    versions: listVersions(job.id).map((v) => ({ ...v, url: `/jobs/${job.id}/${v.file}` })),
    audioBusy: audioBusy(job.id),
    links: {
      mp4: has('out.mp4') && job.status === 'done' ? `/jobs/${job.id}/out.mp4` : null,
      preview: has('preview.jpg') ? `/jobs/${job.id}/preview.jpg` : null,
      prompt: `/jobs/${job.id}/PROMPT.md`,
      brief: has('brief.json') ? `/jobs/${job.id}/brief.json` : null,
    },
    paths: { dir, prompt: path.join(dir, 'PROMPT.md'), scene: path.join(dir, 'scene', 'index.html') },
  };
  if (v.error) v.error = redact(v.error);
  if (withLog) v.log = readLog(job.id, 120).map(redact);
  return v;
}

/** Job vừa tạo: hẹn giờ thì để bộ hẹn giờ lo; manual chỉ chuyển sang waiting_agent; còn lại xếp hàng chạy. */
async function startJob(job) {
  if (job.status === 'scheduled') return; // bộ hẹn giờ sẽ chạy khi tới giờ
  if (resolveMode(job.mode) === 'manual') await runJob(job.id);
  else enqueueJob(job.id, () => runJob(job.id));
}

/** Job dựng thử của nháp "Tạo mẫu từ video": xếp vào hàng đợi chung, trả job khi xong. */
function draftTestRunner(id) {
  return new Promise((resolve) => {
    enqueueJob(id, async () => {
      try { resolve(await runJob(id, { force: true })); } catch (e) { console.error('[draft-test]', id, e.message); resolve(readJob(id)); }
    });
  });
}

let rewriteBusy = false;
let rewriteLast = 0;

const server = http.createServer(async (req, res) => {
  const url = new URL(req.url, `http://${HOST}`);
  const p = decodeURIComponent(url.pathname);
  // Chống DNS rebinding: chỉ nhận Host là 127.0.0.1/localhost đúng cổng.
  if (!ALLOWED_HOSTS.has(String(req.headers.host || '').toLowerCase())) return send(res, 421, { error: 'host không hợp lệ' });
  // Trang web lạ không gửi lệnh ghi vào được (tạo job, cài gói, xoá…): Origin phải là chính app (không có Origin = curl/agent cục bộ).
  if (!['GET', 'HEAD', 'OPTIONS'].includes(req.method) && !originOk(req, ALLOWED_HOSTS)) {
    res.setHeader('Connection', 'close'); res.on('finish', () => req.destroy());
    return send(res, 403, { error: 'origin không hợp lệ' });
  }
  try {
    // ---- Nhật ký (server/logs.mjs): chỉ đọc, đã lọc bí mật ----
    if (handleLogRoute(req, res, p, url, { send, originOk: (r) => originOk(r, ALLOWED_HOSTS), jobsDir: JOBS, editsDir: EDITS, readJob, readEdit: readEditJob })) return;
    // ---- Gói mẫu .lumpack (packs/http.mjs) ----
    if (await handlePackRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS })) return;
    // ---- Edit video của bạn (edit/http.mjs) ----
    if (await handleEditRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS })) return;
    // ---- Giọng của tôi (server/voices-http.mjs) ----
    if (await handleVoiceRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS })) return;
    // ---- Tạo mẫu từ video (packs/drafts-http.mjs): job dựng thử đi qua hàng đợi chung ----
    if (await handleDraftRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS, runTest: draftTestRunner })) return;
    // ---- Kiểm tra máy + khoá Anthropic (server/doctor.mjs) ----
    if (await handleDoctorRoute(req, res, p, url, { send, readBody, originOk: (r) => originOk(r, ALLOWED_HOSTS) })) return;
    // ---- API ----
    if (p === '/api/templates' && req.method === 'GET') return send(res, 200, templateList());
    if (p === '/api/version' && req.method === 'GET') return send(res, 200, { version: PKG_VERSION, update: updateState });
    if (p === '/api/config' && req.method === 'GET') {
      return send(res, 200, { defaultMode: DEFAULT_MODE, autoResolves: resolveMode('auto'), claudeAvailable: !!findClaude(), apiAvailable: config.hasApiKey(), outputDir: !!config.outputDir(), rewriteEngine: resolveRewriteEngine() });
    }
    if (p === '/api/rewrite' && req.method === 'POST') {
      // Chống bấm liên tục: mỗi lúc 1 lượt, cách nhau ≥ 3 giây.
      if (rewriteBusy) return send(res, 429, { error: 'Đang viết lại 1 bản, chờ xong rồi bấm tiếp' });
      if (Date.now() - rewriteLast < 3000) return send(res, 429, { error: 'Bấm chậm lại chút (cách nhau 3 giây)' });
      const body = await readBody(req);
      if (String(body.content || '').length > REWRITE_MAX_CHARS) return send(res, 413, { error: `Nội dung quá dài (tối đa ${REWRITE_MAX_CHARS} ký tự)` });
      rewriteBusy = true;
      try {
        const r = await rewriteScript({ templateId: body.templateId, content: body.content, durationS: body.durationS });
        console.log(`[rewrite] mẫu ${r.templateId}, ${r.durationS}s, ${r.engine}${r.fallbackFrom ? ' (sau khi ' + r.fallbackFrom + ')' : ''}`);
        return send(res, 200, r);
      } catch (e) {
        return send(res, /chưa cấu hình AI/i.test(e.message) ? 503 : 422, { error: e.message });
      } finally {
        rewriteBusy = false; rewriteLast = Date.now();
      }
    }
    if (p === '/api/jobs' && req.method === 'GET') return send(res, 200, listJobs().map((j) => jobView(j)));
    if (p === '/api/jobs' && req.method === 'POST') {
      const body = await readBody(req);
      const job = createJob({ templateId: body.templateId, content: body.content, durationS: body.durationS, aspect: body.aspect, mode: body.mode || DEFAULT_MODE, model: body.model, runAt: body.runAt, source: body.source || 'web', audio: body.audio });
      await startJob(job);
      return send(res, 201, jobView(readJob(job.id), true));
    }
    if (p === '/api/jobs/batch' && req.method === 'POST') {
      // Chọn nhiều mẫu: 1 job / mẫu, cùng nội dung + tuỳ chọn. Kiểm cả lô trước, sai 1 id là từ chối hết.
      const body = await readBody(req);
      if (!Array.isArray(body.templateIds)) return send(res, 400, { error: 'templateIds phải là mảng id mẫu' });
      if (body.templateIds.length > MAX_BATCH) return send(res, 400, { error: `Tối đa ${MAX_BATCH} mẫu mỗi lô` });
      let jobs;
      try {
        jobs = createJobs({ templateIds: body.templateIds, content: body.content, durationS: body.durationS, aspect: body.aspect, mode: body.mode || DEFAULT_MODE, model: body.model, runAt: body.runAt, source: body.source || 'web', audio: body.audio });
      } catch (e) { return send(res, 400, { error: e.message, badIds: e.badIds || [] }); }
      for (const job of jobs) await startJob(job);
      console.log(`[batch] ${jobs.length} job: ${jobs.map((j) => j.templateId).join(', ')}`);
      return send(res, 201, { jobs: jobs.map((j) => jobView(readJob(j.id))) });
    }
    let ms = /^\/api\/jobs\/([\w-]+)\/scene$/.exec(p);
    if (ms && req.method === 'POST') {
      const body = await readBody(req, 2_500_000);
      if (body.audio !== undefined && body.audio !== null) await saveAudioSpec(ms[1], body.audio); // scene/audio.json (AUTHORING §9)
      const r = submitScene(ms[1], body.html, body.brief);
      return send(res, r.ok ? 200 : 422, r);
    }
    ms = /^\/api\/jobs\/([\w-]+)\/preview$/.exec(p);
    if (ms && req.method === 'POST') {
      const r = await previewJob(ms[1]);
      return send(res, r.ok ? 200 : 422, { ok: r.ok, errors: r.errors, preview: r.ok ? `/jobs/${ms[1]}/preview.jpg` : null });
    }
    let m = /^\/api\/jobs\/([\w-]+)$/.exec(p);
    if (m && req.method === 'GET') {
      const job = readJob(m[1]);
      return job ? send(res, 200, jobView(job, true)) : send(res, 404, { error: 'không thấy job' });
    }
    m = /^\/api\/jobs\/([\w-]+)\/render$/.exec(p);
    if (m && req.method === 'POST') {
      const job = readJob(m[1]);
      if (!job) return send(res, 404, { error: 'không thấy job' });
      enqueueJob(job.id, () => renderJob(job.id));
      return send(res, 202, jobView(job, true));
    }
    // ---- âm thanh ----
    if (p === '/api/audio/options' && req.method === 'GET') return send(res, 200, audioOptions());
    if (p === '/api/audio/preview' && req.method === 'GET') {
      const f = await audioPreviewFile(url.searchParams);
      return serveFile(req, res, path.dirname(f), path.basename(f));
    }
    m = /^\/api\/jobs\/([\w-]+)\/audio$/.exec(p);
    if (m && req.method === 'POST') {
      const job = readJob(m[1]);
      if (!job) return send(res, 404, { error: 'không thấy job' });
      if (job.status !== 'done' && !fs.existsSync(path.join(JOBS, job.id, 'out.mp4'))) return send(res, 409, { error: 'video chưa dựng xong' });
      if (audioBusy(job.id)) return send(res, 409, { error: 'đang trộn tiếng cho video này' });
      const body = await readBody(req);
      const prefs = { music: body.music, voice: body.voice, sfx: body.sfx };
      normalizeAudioPrefs({ ...prefs }); // kiểm sớm, sai thì 400
      reAudio(job.id, prefs).catch((e) => console.error('[audio]', job.id, e.message)); // chạy nền; UI hỏi lại GET /api/jobs/:id
      return send(res, 202, { ...jobView(readJob(job.id), true), audioBusy: true });
    }
    m = /^\/api\/jobs\/([\w-]+)\/versions$/.exec(p);
    if (m && req.method === 'GET') return send(res, 200, listVersions(m[1]).map((v) => ({ ...v, url: `/jobs/${m[1]}/${v.file}` })));
    if (p.startsWith('/api/')) return send(res, 404, { error: 'không có API này' });

    // ---- file ----
    if (req.method !== 'GET' && req.method !== 'HEAD') return send(res, 405, { error: 'method' });
    if (p.startsWith('/ref/') && USE_REF) return serveFile(req, res, path.join(TEMPLATES, 'ref'), p.slice(5));
    m = /^\/demo\/(\d{3}\.(?:mp4|webp))$/.exec(p);
    if (m) return serveFile(req, res, DEMO, m[1]);
    m = /^\/thumbs\/(\d{3}\.webp)$/.exec(p);
    if (m) return serveFile(req, res, THUMBS, m[1]);
    m = /^\/poster\/(\d{3})\.svg$/.exec(p);
    if (m) {
      const t = loadCatalog().find((x) => x.id === m[1]);
      return t ? send(res, 200, posterSvg(t), 'image/svg+xml; charset=utf-8') : send(res, 404, { error: 'không thấy mẫu' });
    }
    m = /^\/poster\/p\/([a-z0-9.-]{5,49})\/([a-z][a-z0-9-]{1,31})\.svg$/.exec(p);
    if (m) {
      const r = parsePackRef(`${m[1]}/${m[2]}`) && resolveTemplate(`${m[1]}/${m[2]}`);
      return r ? send(res, 200, posterSvg({ id: r.ref, name: r.meta.name, category: r.meta.category, technique: r.meta.technique }), 'image/svg+xml; charset=utf-8') : send(res, 404, { error: 'không thấy mẫu' });
    }
    m = /^\/jobs\/([\w-]+)\/(versions\/out-\d{1,4}\.mp4)$/.exec(p);
    if (m) return serveFile(req, res, path.join(JOBS, m[1]), m[2]);
    m = /^\/jobs\/([\w-]+)\/(out\.mp4|preview\.jpg|PROMPT\.md|brief\.json)$/.exec(p);
    if (m) return serveFile(req, res, path.join(JOBS, m[1]), m[2]);
    // font: khung xem trước đồ hoạ của Studio chạy sandbox (origin rỗng) → tải font cần CORS
    if (p.startsWith('/fonts/')) { res.setHeader('Access-Control-Allow-Origin', '*'); return serveFile(req, res, path.join(ROOT, 'engine', 'fonts'), p.slice(7)); }
    return serveFile(req, res, PUBLIC, p === '/' ? 'index.html' : p.slice(1));
  } catch (e) {
    return send(res, 400, { error: e.message });
  }
});

markStale();
initEdits(); // edit đang chạy dở khi server tắt → báo lỗi để bấm lại
initVoices(); // giọng nhân bản đang xử lý dở → báo lỗi
initDrafts(); // nháp "Tạo mẫu từ video" đang chạy dở → báo lỗi
// Job queued còn sót (server tắt trước khi kịp chạy) → chạy lại.
for (const j of listJobs()) if (j.status === 'queued' && resolveMode(j.mode) !== 'manual') enqueueJob(j.id, () => runJob(j.id));
// Bộ hẹn giờ: 15 giây kiểm 1 lần, job tới giờ thì xếp hàng chạy.
function tick() { for (const j of dueJobs()) enqueueJob(j.id, () => runJob(j.id, { force: true })); }
setInterval(tick, 15000);
tick();

// Kiểm bản mới trên GitHub (chạy nền, không chặn app): lúc khởi động và 6 giờ/lần. Giao diện đọc qua /api/version.
const PKG_VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
let updateState = null;
function checkUpdateBg() {
  if (process.env.LUMREELS_SKIP_UPDATE === '1') return;
  const p = spawn(process.execPath, [fileURLToPath(new URL('../scripts/update.mjs', import.meta.url)), '--json'], { windowsHide: true });
  let out = '';
  p.stdout.on('data', (d) => { out += d; });
  p.on('error', () => {});
  p.on('close', () => { try { updateState = JSON.parse(out); } catch { /* bỏ qua */ } });
}
setTimeout(checkUpdateBg, 3000);
setInterval(checkUpdateBg, 6 * 3600 * 1000).unref();

server.listen(PORT, HOST, () => {
  console.log(`LumReels: http://${HOST}:${PORT}  (chế độ mặc định: ${DEFAULT_MODE} → ${resolveMode(DEFAULT_MODE)}; OUTPUT_DIR ${config.outputDir() ? 'có' : 'chưa đặt'})`);
});