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.

Chọn nhiều mẫu cùng lúc: 1 job mỗi mẫu (UI, REST /api/jobs/batch, CLI --template 009,045, MCP templateIds)

Lumtekb478d8d253f4
diff --git a/README.md b/README.md
index 1888492..4a9d2d6 100644
--- a/README.md
+++ b/README.md
@@ -30,6 +30,7 @@
| 🎬 **100+ styles** | Faceless explainers, ads and mixed-media: cosmic shaders, low-poly 3D, paper cut-outs, 8-bit pixel art, risograph, terminal UIs… Each style is a text file (palette, fonts, layout, beat-by-beat timing), not a video. |
| ✍️ **AI writes the scene** | Claude writes a fresh scene for every piece of content, then checks its own preview frames and fixes what it sees. A **Rewrite script** button fits your text into the style's slots. |
| 🔊 **Sound included** | 6 music styles and ~30 sound effects, all synthesized and synced to the motion. English voices come from Kokoro and Vietnamese voices from VieNeu, both running locally with edge-tts as fallback. Mixed to −14 LUFS. Swap music or voice without re-rendering the picture. |
+| 🧩 **Many styles at once** | Turn on **Pick multiple**, choose up to 12 styles, type your content once: one video per style (also `POST /api/jobs/batch`, `--template 009,045`, MCP `templateIds`). |
| 🤖 **Built for AI agents** | MCP server, CLI and REST. Claude, Codex or any agent can create a video, submit a scene, preview, render, schedule, and drop the MP4 into a Google Drive folder. |
| ⏱️ **3 seconds to 10 minutes** | Type `90` or `1:30`. Long videos are split into scenes, and every frame is a pure function of time, so renders are deterministic. |
| 🔤 **Typography that holds up** | 25 font families with full Vietnamese diacritics. Missing glyphs, overflowing text and tiny type are flagged before rendering. |
diff --git a/README.vi.md b/README.vi.md
index 3337394..f355f32 100644
--- a/README.vi.md
+++ b/README.vi.md
@@ -30,6 +30,7 @@
| 🎬 **Hơn 100 mẫu phong cách** | Faceless, quảng cáo, đa phong cách: shader vũ trụ, 3D low-poly, giấy cắt, pixel 8-bit, risograph, terminal… Mỗi mẫu là một file mô tả bằng chữ (màu, font, bố cục, nhịp theo giây), không kèm video gốc. |
| ✍️ **AI viết cảnh, không ghép template** | Claude viết cảnh mới cho từng nội dung, tự xem ảnh xem thử và sửa. Nút **Viết lại kịch bản** xếp chữ của bạn vào đúng ô của mẫu. |
| 🔊 **Âm thanh trọn gói** | 6 kiểu nhạc nền, ~30 tiếng động gắn theo chuyển động, giọng đọc tiếng Việt (VieNeu) và tiếng Anh (Kokoro), đều chạy trên máy, dự phòng edge-tts; chuẩn −14 LUFS. Đổi nhạc/giọng không phải dựng lại hình. |
+| 🧩 **Nhiều mẫu một lần** | Bật **Chọn nhiều mẫu**, chọn tối đa 12 mẫu, gõ nội dung một lần: mỗi mẫu ra 1 video (cả `POST /api/jobs/batch`, `--template 009,045`, MCP `templateIds`). |
| 🤖 **Cho AI agent gọi thẳng** | MCP server, CLI và REST. Claude, Codex hay agent bất kỳ: tạo video, gửi cảnh, xem thử, render, hẹn giờ, chép MP4 ra Google Drive. |
| ⏱️ **3 giây tới 10 phút** | Gõ `90` hoặc `1:30`. Video dài tự chia cảnh, mỗi khung là hàm thuần theo thời gian nên render ổn định. |
| 🇻🇳 **Tiếng Việt chuẩn** | 25 họ font có dấu tiếng Việt, tự kiểm font thiếu dấu, chữ tràn khung, chữ quá nhỏ trước khi render. |
diff --git a/cli.mjs b/cli.mjs
index 988b6d6..2a5700a 100644
--- a/cli.mjs
+++ b/cli.mjs
@@ -1,6 +1,6 @@
#!/usr/bin/env node
// CLI cho người và AI agent.
-// node cli.mjs make --template 009 --content <file|chuỗi> [--duration 8] [--mode manual|agent|claude|api|auto] [--at 2026-11-28T07:00] [--json]
+// node cli.mjs make --template 009[,045,062] --content <file|chuỗi> [--duration 8] [--mode manual|agent|claude|api|auto] [--at 2026-11-28T07:00] [--json]
// node cli.mjs rewrite --template 009 --content <file|chuỗi> [--duration 30] [--engine auto|api|claude] [--json]
// node cli.mjs run-due (chạy các job hẹn giờ đã tới giờ — cho Windows Task Scheduler)
// node cli.mjs render <jobId> [--quality draft|looks|delivery] [--audio file]
@@ -9,7 +9,7 @@
// node cli.mjs show <jobId>
// node cli.mjs templates [--json]
import fs from 'node:fs';
-import { createJob, runJob, renderJob, runDue, listJobs, readJob, readLog, jobPaths, loadCatalog, hasGuidance, exportOutput } from './generator/jobs.mjs';
+import { createJob, createJobs, parseTemplateIds, MAX_BATCH, runJob, renderJob, runDue, listJobs, readJob, readLog, jobPaths, loadCatalog, hasGuidance, exportOutput } from './generator/jobs.mjs';
import { parseArgs, probe } from './engine/lib.mjs';
import { rewriteScript } from './generator/rewrite.mjs';
@@ -21,7 +21,9 @@ const audioOpts = () => ({ music: opt.music === true ? undefined : opt.music, vo
function usage() {
console.log(`LumReels CLI
- make --template <id> --content <file|chuỗi> [--duration 8] [--mode manual|claude|api|auto] [--model auto|opus|sonnet|haiku] [--at <giờ>] [--json]
+ make --template <id>[,<id>…] --content <file|chuỗi> [--duration 8] [--mode manual|claude|api|auto] [--model auto|opus|sonnet|haiku] [--at <giờ>] [--json]
+ --template 009,045,062 : nhiều mẫu (tối đa ${MAX_BATCH}) → 1 job mỗi mẫu, cùng nội dung + tuỳ chọn, chạy lần lượt.
+ Kiểm hết trước: 1 id sai / chưa có guidance thì không tạo job nào.
--music <style|auto|none> --voice <tên giọng|auto|none> --no-sfx : âm thanh (mặc định auto, auto, có sfx)
--duration: 3 giây → 10 phút, số giây (90) hoặc phút:giây (1:30, 10:00). Mặc định 8.
manual (mặc định): ghi jobs/<id>/PROMPT.md, job ở trạng thái waiting_agent. Agent viết
@@ -59,15 +61,21 @@ try {
}
process.exit(0);
} else if (cmd === 'make') {
- if (!opt.template || !opt.content) { usage(); process.exit(2); }
+ if (!opt.template || opt.template === true || !opt.content) { usage(); process.exit(2); }
const content = readContent(String(opt.content));
const mode = opt.mode || process.env.VIDEOAI_CLI_MODE || 'manual';
- const job = createJob({ templateId: String(opt.template), content, durationS: opt.duration === true ? undefined : opt.duration, mode, model: typeof opt.model === 'string' ? opt.model : undefined, runAt: opt.at, source: 'cli',
- audio: (({ music, voice, sfx }) => ({ music: music ?? 'auto', voice: voice ?? 'auto', sfx: sfx ?? true }))(audioOpts()) });
- const p = jobPaths(job.id);
- const done = await runJob(job.id);
- if (opt.json) out({ ...done, paths: p });
- else {
+ const ids = parseTemplateIds(String(opt.template));
+ const input = { content, durationS: opt.duration === true ? undefined : opt.duration, mode, model: typeof opt.model === 'string' ? opt.model : undefined, runAt: opt.at, source: 'cli',
+ audio: (({ music, voice, sfx }) => ({ music: music ?? 'auto', voice: voice ?? 'auto', sfx: sfx ?? true }))(audioOpts()) };
+ // 1 mẫu: như cũ. Nhiều mẫu: kiểm cả lô rồi tạo hết, sau đó chạy lần lượt từng job.
+ const jobs = ids.length > 1 ? createJobs({ ...input, templateIds: ids }) : [createJob({ ...input, templateId: ids[0] || String(opt.template) })];
+ const results = [];
+ for (const [i, job] of jobs.entries()) {
+ const p = jobPaths(job.id);
+ const done = await runJob(job.id);
+ results.push({ ...done, paths: p });
+ if (opt.json) continue;
+ if (jobs.length > 1) console.log(`\n[${i + 1}/${jobs.length}] mẫu ${job.templateId}`);
console.log(`job: ${job.id} trạng thái: ${done.status}`);
if (done.status === 'scheduled') console.log(`Hẹn chạy lúc: ${new Date(done.runAt).toLocaleString('vi-VN')} — server đang bật sẽ tự chạy, hoặc: node cli.mjs run-due`);
else if (done.status === 'waiting_agent') {
@@ -75,7 +83,8 @@ try {
} else if (done.status === 'done') console.log(`MP4: ${p.mp4}\nPreview: ${p.preview}`);
else if (done.error) console.log('Lỗi: ' + done.error);
}
- process.exit(done.status === 'error' ? 1 : 0);
+ if (opt.json) out(jobs.length > 1 ? { jobs: results } : results[0]);
+ process.exit(results.some((d) => d.status === 'error') ? 1 : 0);
} else if (cmd === 'render') {
if (!pos[0]) { usage(); process.exit(2); }
const done = await renderJob(pos[0], { quality: opt.quality || 'looks', audio: opt.audio });
diff --git a/docs/CHI-TIET.md b/docs/CHI-TIET.md
index 158c049..be6d1b9 100644
--- a/docs/CHI-TIET.md
+++ b/docs/CHI-TIET.md
@@ -48,14 +48,21 @@ Trạng thái: `scheduled → queued → generating → (waiting_agent) → prev
Nút **Viết lại kịch bản** cạnh ô Nội dung (và `POST /api/rewrite {templateId, content, durationS}` → `{script, notes, engine, usage}`, CLI `node cli.mjs rewrite`, MCP `rewrite_script`): AI đọc §1–§3 và §10 guidance của mẫu, viết lại nội dung thành các ô nội dung đúng giới hạn ký tự, chia cảnh theo thời lượng; giữ ý, số liệu, thương hiệu, CTA; không bịa số liệu thật. Nội dung ≤ 4000 ký tự, tối đa 90 giây/lượt, server chỉ chạy 1 lượt một lúc (cách nhau ≥ 3 giây). Lõi: `generator/rewrite.mjs`.
Engine: `api` (có `ANTHROPIC_API_KEY`, model `REWRITE_MODEL`) → `claude` (Claude Code headless `claude -p --tools ""`, không tool, không MCP, chạy trong thư mục tạm trống) → chưa có cả hai thì báo "Chưa cấu hình AI". Ở `auto`, khoá API bị từ chối (401/403) mà máy có Claude Code thì tự chuyển sang `claude` và ghi rõ trong kết quả (`fallbackFrom`).
+## Chọn nhiều mẫu cùng lúc
+Bật công tắc **Chọn nhiều mẫu** cạnh bộ lọc, bấm các mẫu (tối đa 12; thẻ đang chọn có số thứ tự), gõ nội dung một lần, bấm **Dựng N video**: app tạo **1 job cho mỗi mẫu**, cùng nội dung, thời lượng, âm thanh, chế độ, model, giờ hẹn. Model "Tự chọn" thì mỗi job tự chọn theo mẫu của nó (3D/shader → Opus, 2D → Sonnet). Khung bên phải hiện dải ảnh các mẫu đã chọn (× để bỏ từng mẫu, "Bỏ chọn hết"). "Viết lại kịch bản" chỉ dùng khi chọn 1 mẫu (mỗi mẫu có ô nội dung khác nhau). Tắt công tắc thì quay về chọn 1 (giữ mẫu đầu tiên).
+Cả lô được kiểm **trước** khi tạo (`validateBatch` trong `generator/jobs.mjs`): 1 id sai hoặc chưa có guidance thì không tạo job nào và báo rõ id nào. Job tạo xong xếp hàng như job đơn (mỗi lúc chạy 1 job).
+- REST: `POST /api/jobs/batch {templateIds:["009","045"], content, durationS, mode, model, runAt, audio}` → `201 {jobs:[...]}`; lỗi → `400 {error, badIds}`.
+- CLI: `node cli.mjs make --template 009,045,062 --content nd.txt [--mode manual …]` — tạo hết rồi chạy lần lượt, in từng job (`--json` → `{jobs:[...]}`).
+- MCP: `create_video` nhận `templateIds` (mảng, tối đa 12) thay cho `templateId`, trả `{count, jobs:[{jobId, templateId, status, promptFile?}]}` (chế độ agent: đọc `promptFile` của từng job).
+
## Cổng cho agent
-**MCP** (stdio): `node mcp/server.mjs` — tool `list_templates`, `get_template`, `rewrite_script`, `create_video` (`durationS` 3–600 hoặc `"1:30"`), `submit_scene`, `preview_job` (trả ảnh), `render_job`, `get_job`, `list_jobs`. Thử: `node scripts/mcp-smoke.mjs`.
+**MCP** (stdio): `node mcp/server.mjs` — tool `list_templates`, `get_template`, `rewrite_script`, `create_video` (`durationS` 3–600 hoặc `"1:30"`; `templateIds` cho nhiều mẫu), `submit_scene`, `preview_job` (trả ảnh), `render_job`, `get_job`, `list_jobs`. Thử: `node scripts/mcp-smoke.mjs`.
**CLI**
```
node cli.mjs templates
node cli.mjs rewrite --template 009 --content nd.txt [--duration 30] [--engine auto|api|claude] [--json]
-node cli.mjs make --template 009 --content nd.txt [--duration 8|90|1:30] [--mode manual|agent|claude|api|auto] [--at 2026-11-28T07:00] [--json]
+node cli.mjs make --template 009[,045,062] --content nd.txt [--duration 8|90|1:30] [--mode manual|agent|claude|api|auto] [--at 2026-11-28T07:00] [--json]
node cli.mjs render <jobId> [--quality draft|looks|delivery] [--audio voice.mp3]
node cli.mjs run-due # cho Windows Task Scheduler
node cli.mjs list | show <jobId>
@@ -64,7 +71,7 @@ node engine/preview.mjs <sceneDir> [-o preview.jpg] [--frame 3.5] # lưới 16
node engine/render.mjs <sceneDir> -o out.mp4 [--audio file]
node engine/fontcheck.mjs <sceneDir> [--readonly] # FONT_FALLBACK / OUTSIDE / WEIGHT / DIGITS / SMALL / DONG
```
-**REST** (127.0.0.1:4400): `GET /api/templates`, `GET|POST /api/jobs`, `GET /api/jobs/:id`, `POST /api/rewrite`, `POST /api/jobs/:id/scene` `{html, brief}`, `POST /api/jobs/:id/preview`, `POST /api/jobs/:id/render`, `GET /api/config`. Chỉ nhận Host `127.0.0.1`/`localhost`.
+**REST** (127.0.0.1:4400): `GET /api/templates`, `GET|POST /api/jobs`, `POST /api/jobs/batch` `{templateIds[], …}`, `GET /api/jobs/:id`, `POST /api/rewrite`, `POST /api/jobs/:id/scene` `{html, brief}`, `POST /api/jobs/:id/preview`, `POST /api/jobs/:id/render`, `GET /api/config`. Chỉ nhận Host `127.0.0.1`/`localhost`.
## Cây thư mục
```
diff --git a/generator/jobs.mjs b/generator/jobs.mjs
index 4fca5d6..e66b1da 100644
--- a/generator/jobs.mjs
+++ b/generator/jobs.mjs
@@ -147,6 +147,58 @@ export function createJob(input) {
return job;
}
+/** Tối đa số mẫu trong 1 lô (chọn nhiều mẫu cùng lúc). */
+export const MAX_BATCH = 12;
+/** "009,45, 062" | ['009', 45] → ['009','045','062'] (bỏ trùng, giữ thứ tự). */
+export function parseTemplateIds(v) {
+ const raw = Array.isArray(v) ? v : String(v ?? '').split(/[\s,;]+/);
+ const ids = [];
+ for (const x of raw) {
+ const s = String(x ?? '').trim();
+ if (!s) continue;
+ const id = /^\d{1,3}$/.test(s) ? s.padStart(3, '0') : s;
+ if (!ids.includes(id)) ids.push(id);
+ }
+ return ids;
+}
+/**
+ * Kiểm cả lô TRƯỚC khi tạo (sai 1 thì từ chối cả lô, không tạo job nào): id phải có trong catalog + có guidance,
+ * và các trường chung (nội dung, thời lượng, chế độ, model, giờ hẹn, âm thanh) phải hợp lệ. Trả danh sách id đã chuẩn hoá.
+ */
+export function validateBatch(input) {
+ const ids = parseTemplateIds(input.templateIds);
+ if (!ids.length) throw new Error('Thiếu templateIds (chọn ít nhất 1 mẫu)');
+ if (ids.length > MAX_BATCH) throw new Error(`Tối đa ${MAX_BATCH} mẫu mỗi lô (đang có ${ids.length})`);
+ const cat = new Map(loadCatalog().map((t) => [t.id, t]));
+ const unknown = ids.filter((id) => !cat.has(id));
+ const noGuide = ids.filter((id) => cat.has(id) && !hasGuidance(id));
+ if (unknown.length || noGuide.length) {
+ const parts = [];
+ if (unknown.length) parts.push(`không có mẫu ${unknown.join(', ')}`);
+ if (noGuide.length) parts.push(`mẫu ${noGuide.join(', ')} chưa có guidance`);
+ const err = new Error(`Từ chối cả lô: ${parts.join('; ')}`);
+ err.badIds = [...unknown, ...noGuide];
+ throw err;
+ }
+ const content = String(input.content || '').trim();
+ if (!content) throw new Error('Thiếu nội dung');
+ if (content.length > 4000) throw new Error('Nội dung quá dài (tối đa 4000 ký tự)');
+ parseDuration(input.durationS);
+ if ((input.aspect || '9:16') !== '9:16') throw new Error('Hiện chỉ hỗ trợ 9:16 (1080x1920)');
+ const mode = input.mode === 'agent' ? 'manual' : (input.mode || 'manual');
+ if (!MODES.includes(mode)) throw new Error(`Chế độ không hợp lệ: ${mode} (auto|api|claude|manual|agent)`);
+ parseRunAt(input.runAt);
+ normalizeAudioPrefs(input.audio && typeof input.audio === 'object' ? { ...input.audio } : input.audio);
+ for (const id of ids) resolveModel(input.model, cat.get(id).technique);
+ return ids;
+}
+/** Tạo 1 job cho mỗi mẫu (cùng nội dung/thời lượng/âm thanh/chế độ/model). Kiểm hết trước (validateBatch). Trả mảng job. */
+export function createJobs(input) {
+ const ids = validateBatch(input);
+ const { templateIds: _ignored, ...common } = input;
+ return ids.map((templateId) => createJob({ ...common, templateId }));
+}
+
/** auto → api (có ANTHROPIC_API_KEY) → claude (có lệnh claude) → manual. */
export function resolveMode(mode) {
if (mode !== 'auto') return mode;
diff --git a/mcp/server.mjs b/mcp/server.mjs
index 27cc0ca..b2fbfda 100644
--- a/mcp/server.mjs
+++ b/mcp/server.mjs
@@ -11,7 +11,7 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { z } from 'zod';
import {
- ROOT, MAX_DURATION_S, loadCatalog, templateName, hasGuidance, guidancePath, createJob, runJob, renderJob, previewJob, submitScene,
+ ROOT, MAX_DURATION_S, MAX_BATCH, loadCatalog, templateName, hasGuidance, guidancePath, createJob, createJobs, runJob, renderJob, previewJob, submitScene,
readJob, listJobs, readLog, jobPaths, jobDir, resolveMode, jobActive,
} from '../generator/jobs.mjs';
import { rewriteScript } from '../generator/rewrite.mjs';
@@ -83,15 +83,40 @@ server.registerTool('get_template', {
return { content: [text(`# GUIDANCE mẫu ${tid}\n\n${fs.readFileSync(guidancePath(tid), 'utf8')}\n\n---\n# AUTHORING (contract viết cảnh)\n\n${fs.readFileSync(AUTHORING, 'utf8')}`)] };
});
+/** Job vừa tạo (1 mẫu) → nội dung trả về cho client MCP. withPrompt=false: không kèm PROMPT (dùng khi tạo nhiều job). */
+async function startForMcp(job, mode, withPrompt = true) {
+ const p = jobPaths(job.id);
+ if (job.status === 'scheduled') {
+ const note = 'Sẽ chạy khi tới giờ nếu server app đang bật (npm start) hoặc Task Scheduler gọi `node cli.mjs run-due`.';
+ if (mode === 'agent') {
+ return { info: { jobId: job.id, templateId: job.templateId, status: 'scheduled', runAt: job.runAt, note, promptFile: p.prompt, next: 'Viết cảnh theo PROMPT và submit_scene TRƯỚC giờ hẹn; tới giờ app tự render và chép ra OUTPUT_DIR.' },
+ prompt: withPrompt ? fs.readFileSync(p.prompt, 'utf8') : null };
+ }
+ return { info: { jobId: job.id, templateId: job.templateId, status: 'scheduled', runAt: job.runAt, note } };
+ }
+ if (mode === 'agent' || resolveMode('auto') === 'manual') {
+ const done = await runJob(job.id);
+ return { info: { jobId: job.id, templateId: job.templateId, status: done.status, promptFile: p.prompt,
+ next: 'Viết TOÀN BỘ scene/index.html theo PROMPT, gọi submit_scene({jobId, html, brief}), rồi preview_job để tự nhìn và sửa (≤2 vòng), cuối cùng render_job.' },
+ prompt: withPrompt ? fs.readFileSync(p.prompt, 'utf8') : null };
+ }
+ spawnDetached(['run', job.id]); // tiến trình riêng: tắt client vẫn chạy tiếp
+ return { info: { jobId: job.id, templateId: job.templateId, status: 'queued', engine: resolveMode('auto'), note: 'Đang tự sinh cảnh + render (1–5 phút) ở tiến trình nền. Gọi get_job để xem trạng thái.' } };
+}
+
server.registerTool('create_video', {
title: 'Tạo video',
description: [
- 'Tạo 1 job video từ mẫu + nội dung. mode "auto": app tự sinh cảnh (Claude API → Claude Code) rồi render, trả jobId ngay; theo dõi bằng get_job.',
+ 'Tạo job video từ mẫu + nội dung. Truyền templateId (1 mẫu) HOẶC templateIds (mảng, tối đa ' + MAX_BATCH + ' mẫu): mỗi mẫu 1 job, cùng nội dung/thời lượng/âm thanh/chế độ/model;',
+ 'kiểm cả lô trước, 1 id sai hoặc chưa có guidance thì không tạo job nào. Nhiều mẫu thì trả {jobs:[...]}, mỗi job có promptFile (đọc file đó thay vì PROMPT kèm theo).',
+ 'mode "auto": app tự sinh cảnh (Claude API → Claude Code) rồi render, trả jobId ngay; theo dõi bằng get_job. model "auto" thì mỗi job tự chọn theo mẫu của nó.',
'mode "agent": trả về PROMPT; chính mày viết scene/index.html theo PROMPT rồi gọi submit_scene → preview_job → render_job.',
'runAt (ISO, vd 2026-11-28T07:00:00+07:00): hẹn giờ; job ở trạng thái scheduled, chạy khi tới giờ (cần server app đang bật hoặc Task Scheduler gọi run-due).',
].join(' '),
inputSchema: {
- templateId: z.string().regex(/^\d{1,3}$/),
+ templateId: z.string().regex(/^\d{1,3}$/).optional().describe('1 mẫu. Dùng templateIds cho nhiều mẫu.'),
+ templateIds: z.array(z.string().regex(/^\d{1,3}$/)).min(1).max(MAX_BATCH).optional()
+ .describe(`Nhiều mẫu (tối đa ${MAX_BATCH}), thay cho templateId: tạo 1 job mỗi mẫu với cùng nội dung + tuỳ chọn.`),
content: z.string().min(5).max(4000),
mode: z.enum(['auto', 'agent']).default('auto'),
model: z.enum(['auto', 'opus', 'sonnet', 'haiku']).optional().describe('Model viết cảnh (chế độ auto). auto = Opus cho mẫu 3D/shader, Sonnet cho mẫu 2D.'),
@@ -100,31 +125,22 @@ server.registerTool('create_video', {
runAt: z.string().optional(),
audio: audioSchema.optional().describe('Âm thanh. Mặc định {music:"auto", voice:"auto", sfx:true}: AI chọn nhạc/tiếng động theo mẫu, chỉ đọc lời khi mẫu có narration.'),
},
-}, async ({ templateId, content, mode, model, durationS, runAt, audio }) => {
- let job;
- try {
- job = createJob({ templateId, content, durationS, mode: mode === 'agent' ? 'manual' : 'auto', model, runAt, source: 'mcp', audio });
- } catch (e) { return fail(e.message); }
- const p = jobPaths(job.id);
- if (job.status === 'scheduled') {
- const note = 'Sẽ chạy khi tới giờ nếu server app đang bật (npm start) hoặc Task Scheduler gọi `node cli.mjs run-due`.';
- if (mode === 'agent') {
- return { content: [
- json({ jobId: job.id, status: 'scheduled', runAt: job.runAt, note, next: 'Viết cảnh theo PROMPT dưới và submit_scene TRƯỚC giờ hẹn; tới giờ app tự render và chép ra OUTPUT_DIR.' }),
- text(fs.readFileSync(p.prompt, 'utf8')),
- ] };
- }
- return { content: [json({ jobId: job.id, status: 'scheduled', runAt: job.runAt, note })] };
- }
- if (mode === 'agent' || resolveMode('auto') === 'manual') {
- const done = await runJob(job.id);
- return { content: [
- json({ jobId: job.id, status: done.status, next: 'Viết TOÀN BỘ scene/index.html theo PROMPT dưới, gọi submit_scene({jobId, html, brief}), rồi preview_job để tự nhìn và sửa (≤2 vòng), cuối cùng render_job.', promptFile: p.prompt }),
- text(fs.readFileSync(p.prompt, 'utf8')),
- ] };
+}, async ({ templateId, templateIds, content, mode, model, durationS, runAt, audio }) => {
+ if (templateId && templateIds) return fail('Chỉ truyền 1 trong 2: templateId hoặc templateIds');
+ if (!templateId && !templateIds) return fail('Thiếu templateId (1 mẫu) hoặc templateIds (nhiều mẫu)');
+ const common = { content, durationS, mode: mode === 'agent' ? 'manual' : 'auto', model, runAt, source: 'mcp', audio };
+ if (templateIds && templateIds.length > 1) {
+ let jobs;
+ try { jobs = createJobs({ ...common, templateIds }); } catch (e) { return fail(e.message); }
+ const list = [];
+ for (const job of jobs) list.push((await startForMcp(job, mode, false)).info);
+ const next = mode === 'agent' ? 'Với từng job: đọc promptFile, viết scene/index.html, submit_scene → preview_job → render_job.' : 'Gọi get_job từng jobId để xem trạng thái.';
+ return { content: [json({ count: list.length, jobs: list, next })] };
}
- spawnDetached(['run', job.id]); // tiến trình riêng: tắt client vẫn chạy tiếp
- return { content: [json({ jobId: job.id, status: 'queued', engine: resolveMode('auto'), note: 'Đang tự sinh cảnh + render (1–5 phút) ở tiến trình nền. Gọi get_job để xem trạng thái.' })] };
+ let job;
+ try { job = createJob({ ...common, templateId: templateId || templateIds[0] }); } catch (e) { return fail(e.message); }
+ const r = await startForMcp(job, mode, true);
+ return { content: r.prompt ? [json(r.info), text(r.prompt)] : [json(r.info)] };
});
server.registerTool('rewrite_script', {
diff --git a/server/public/app.js b/server/public/app.js
index f45aee0..6e350c7 100644
--- a/server/public/app.js
+++ b/server/public/app.js
@@ -34,7 +34,12 @@
const durS = () => parseDur($('#duration').value).s;
let templates = [];
- let selected = null;
+ // Mẫu đang chọn (theo thứ tự bấm). Chế độ thường: tối đa 1. "Chọn nhiều mẫu": tối đa MAX_PICK, mỗi mẫu 1 job.
+ const MAX_PICK = 12;
+ let picks = [];
+ let multi = false;
+ const one = () => (picks.length === 1 ? picks[0] : null);
+ const pickIndex = (id) => picks.findIndex((t) => t.id === id);
let cat = '';
let pollTimer = null;
const JOB_PAGE = 6;
@@ -83,29 +88,85 @@
$('#grid').innerHTML = '<div class="empty-grid">Không có mẫu khớp. Thử bỏ lọc hoặc đổi từ khoá.</div>';
return;
}
- $('#grid').innerHTML = list.map((t) => `
- <div class="tpl ${t.hasGuidance ? '' : 'off'} ${selected?.id === t.id ? 'sel' : ''}" data-id="${t.id}"
- role="button" tabindex="0" aria-disabled="${!t.hasGuidance}" aria-pressed="${selected?.id === t.id}"
- aria-label="Mẫu ${t.id}: ${esc(t.name)}${t.hasGuidance ? '' : ' (chưa có guidance, chưa dùng được)'}">
+ const focusId = document.activeElement?.closest?.('#grid .tpl')?.dataset.id;
+ $('#grid').classList.toggle('multi', multi);
+ $('#grid').innerHTML = list.map((t) => { const k = pickIndex(t.id); return `
+ <div class="tpl ${t.hasGuidance ? '' : 'off'} ${k >= 0 ? 'sel' : ''}" data-id="${t.id}"
+ role="button" tabindex="0" aria-disabled="${!t.hasGuidance}" aria-pressed="${k >= 0}"
+ aria-label="Mẫu ${t.id}: ${esc(t.name)}${t.hasGuidance ? '' : ' (chưa có guidance, chưa dùng được)'}${multi && k >= 0 ? `, đã chọn thứ ${k + 1}` : ''}">
+ ${multi && k >= 0 ? `<span class="order" aria-hidden="true">${k + 1}</span>` : ''}
${t.thumb ? `<img class="thumb" src="${t.thumb}" alt="" loading="lazy" decoding="async" width="540" height="960">`
: '<div class="thumb ph">chưa có ảnh</div>'}
<span class="badge ${t.hasGuidance ? 'ready' : ''}">${t.hasGuidance ? 'Sẵn sàng' : 'Chưa có guidance'}</span>
${t.video ? `<button class="play" data-play="${t.id}" aria-label="${t.videoKind === 'demo' ? 'Xem video demo' : 'Xem video tham chiếu'} mẫu ${t.id}"><svg viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg></button>` : ''}
<div class="meta"><div class="id">${t.id} · ${esc(CAT[t.category] || t.category)}</div><div class="t">${esc(t.name)}</div></div>
- </div>`).join('');
+ </div>`; }).join('');
+ if (focusId) document.querySelector(`#grid .tpl[data-id="${focusId}"]`)?.focus({ preventScroll: true });
+ }
+
+ // Báo nhẹ (tự ẩn), vd chọn quá 12 mẫu.
+ let noteTimer = null;
+ function note(msg) {
+ const el = $('#pickNote');
+ el.textContent = msg;
+ clearTimeout(noteTimer);
+ if (msg) noteTimer = setTimeout(() => { el.textContent = ''; }, 4000);
}
function pick(id) {
const t = templates.find((x) => x.id === id);
if (!t || !t.hasGuidance) return;
- selected = t;
+ if (!multi) picks = [t];
+ else {
+ const k = pickIndex(id);
+ if (k >= 0) picks.splice(k, 1);
+ else if (picks.length >= MAX_PICK) { note(`Tối đa ${MAX_PICK} mẫu mỗi lần dựng. Bỏ bớt 1 mẫu rồi chọn tiếp.`); return; }
+ else picks.push(t);
+ }
+ note('');
+ picksChanged();
+ }
+ function unpick(id) { const k = pickIndex(id); if (k >= 0) { picks.splice(k, 1); picksChanged(); } }
+ function setMulti(on) {
+ multi = on;
+ $('#multiPick').checked = on;
+ if (!on) picks = picks.slice(0, 1); // tắt: quay về chọn 1, giữ mẫu đầu tiên
+ note('');
+ picksChanged();
+ }
+
+ function picksChanged() {
renderGrid();
- $('#picked').className = 'picked';
+ renderPicked();
window.dispatchEvent(new Event('lumreels:picked'));
- $('#picked').innerHTML = `${t.thumb ? `<img src="${t.thumb}" alt="">` : ''}<div><div class="t">${t.id} · ${esc(t.name)}</div><div class="d">${esc(t.blurb || t.genre || '')}</div></div>`;
+ updateWhen();
updateGo();
}
+ function renderPicked() {
+ const box = $('#picked');
+ if (!picks.length) {
+ box.className = 'picked empty';
+ box.textContent = multi ? `Đang chọn nhiều: bấm các mẫu sáng màu bên trái (tối đa ${MAX_PICK}), mỗi mẫu ra 1 video.` : 'Chưa chọn mẫu. Bấm 1 mẫu sáng màu bên trái.';
+ return;
+ }
+ if (!multi) {
+ const t = picks[0];
+ box.className = 'picked';
+ box.innerHTML = `${t.thumb ? `<img src="${t.thumb}" alt="">` : ''}<div><div class="t">${t.id} · ${esc(t.name)}</div><div class="d">${esc(t.blurb || t.genre || '')}</div></div>`;
+ return;
+ }
+ box.className = 'picked multi';
+ box.innerHTML = `<div class="pm-head"><span class="t">Đã chọn ${picks.length} mẫu</span>
+ <button type="button" class="mini" data-clear>Bỏ chọn hết</button></div>
+ <ul class="strip" aria-label="Các mẫu đã chọn">${picks.map((t, i) => `
+ <li class="pk" title="${t.id} · ${esc(t.name)}">
+ ${t.thumb ? `<img src="${t.thumb}" alt="">` : '<span class="ph"></span>'}
+ <span class="n" aria-hidden="true">${i + 1}</span>
+ <button type="button" class="rm" data-unpick="${t.id}" aria-label="Bỏ mẫu ${t.id}: ${esc(t.name)}">×</button>
+ </li>`).join('')}</ul>`;
+ }
+
function openViewer(id) {
const t = templates.find((x) => x.id === id);
if (!t) return;
@@ -124,12 +185,18 @@
$('#chars').textContent = n;
const enough = $('#content').value.trim().length >= 10;
const dur = !!durS();
- const ok = !!selected && enough && dur;
+ const ok = picks.length > 0 && enough && dur;
$('#go').disabled = !ok;
- $('#go').title = !selected ? 'Chọn 1 mẫu trước' : !enough ? 'Nội dung tối thiểu 10 ký tự' : !dur ? 'Thời lượng chưa đúng' : '';
+ $('#go').title = !picks.length ? 'Chọn mẫu trước' : !enough ? 'Nội dung tối thiểu 10 ký tự' : !dur ? 'Thời lượng chưa đúng' : '';
const rw = $('#rewrite');
- rw.disabled = !ok || rwBusy;
- rw.title = rwBusy ? 'Đang viết lại…' : !selected ? 'Chọn 1 mẫu trước' : !enough ? 'Gõ nội dung trước (tối thiểu 10 ký tự)' : !dur ? 'Thời lượng chưa đúng' : '';
+ const many = picks.length > 1;
+ rw.disabled = !ok || many || rwBusy;
+ rw.title = rwBusy ? 'Đang viết lại…' : !picks.length ? 'Chọn 1 mẫu trước' : many ? 'Chỉ viết lại được khi chọn 1 mẫu' : !enough ? 'Gõ nội dung trước (tối thiểu 10 ký tự)' : !dur ? 'Thời lượng chưa đúng' : '';
+ const hint = $('#rwHint');
+ hint.classList.toggle('bad', many);
+ hint.textContent = many
+ ? `Viết lại kịch bản tắt vì đang chọn ${picks.length} mẫu: mỗi mẫu có ô nội dung khác nhau. Muốn AI viết lại thì chọn 1 mẫu; còn không, cả ${picks.length} video dùng chung nội dung đang gõ.`
+ : 'Viết lại kịch bản: AI xếp nội dung vào đúng ô của mẫu đang chọn và thời lượng bên dưới, giữ nguyên số liệu, tên kênh, CTA.';
}
// ---------- thời lượng ----------
@@ -155,6 +222,7 @@
let rwUndo = null; // nội dung trước khi bấm "Dùng bản này"
function rwShow(cls, html) { const b = $('#rwBox'); b.className = 'rw ' + cls; b.innerHTML = html; b.hidden = !html; }
async function rewrite() {
+ const selected = one();
if (rwBusy || !selected) return;
const dur = durS();
rwBusy = true; rwResult = null;
@@ -206,16 +274,21 @@
async function submit() {
$('#formErr').textContent = '';
const btn = $('#go');
+ if (!picks.length) return;
btn.disabled = true; btn.classList.add('busy'); btn.querySelector('span').textContent = 'Đang gửi';
+ const batch = picks.length > 1;
+ const common = { content: $('#content').value, durationS: durS(), mode: $('#mode').value, model: $('#model').value, runAt: runAtValue(), audio: window.LumAudio?.value() };
try {
- const r = await fetch('/api/jobs', {
+ const r = await fetch(batch ? '/api/jobs/batch' : '/api/jobs', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ templateId: selected.id, content: $('#content').value, durationS: durS(), mode: $('#mode').value, model: $('#model').value, runAt: runAtValue(), audio: window.LumAudio?.value() }),
+ body: JSON.stringify(batch ? { templateIds: picks.map((t) => t.id), ...common } : { templateId: picks[0].id, ...common }),
});
const j = await r.json();
if (!r.ok) throw new Error(j.error || 'Tạo job lỗi');
+ const created = batch ? j.jobs : [j];
+ if (created.length > JOB_PAGE) showAll = true; // cả lô đều hiện trong danh sách
await loadJobs();
- document.getElementById('job-' + j.id)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ document.getElementById('job-' + created[0].id)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
} catch (e) {
$('#formErr').textContent = e.message + '. Sửa rồi bấm lại.';
} finally {
@@ -318,6 +391,12 @@
$('#grid').addEventListener('keydown', (e) => {
if ((e.key === 'Enter' || e.key === ' ') && e.target.classList.contains('tpl')) { e.preventDefault(); pick(e.target.dataset.id); }
});
+ $('#multiPick').addEventListener('change', (e) => setMulti(e.target.checked));
+ $('#picked').addEventListener('click', (e) => {
+ const rm = e.target.closest('[data-unpick]');
+ if (rm) { unpick(rm.dataset.unpick); ($('#picked [data-unpick]') || $('#multiPick')).focus(); return; }
+ if (e.target.closest('[data-clear]')) { picks = []; picksChanged(); $('#multiPick').focus(); }
+ });
$('#q').addEventListener('input', renderGrid);
$('#readyOnly').addEventListener('change', renderGrid);
document.querySelectorAll('.chip').forEach((c) => c.addEventListener('click', () => {
@@ -337,7 +416,8 @@
function updateWhen() {
const v = $('#runAt').value;
const btn = $('#go').querySelector('span');
- if (!btn.closest('.busy')) btn.textContent = v ? 'Hẹn dựng video' : 'Dựng video';
+ const n = picks.length > 1 ? `${picks.length} video` : 'video';
+ if (!btn.closest('.busy')) btn.textContent = v ? `Hẹn dựng ${n}` : `Dựng ${n}`;
$('#clearAt').hidden = !v;
}
$('#runAt').addEventListener('input', updateWhen);
@@ -359,6 +439,8 @@
const MODEL_NAME = { opus: 'Opus', sonnet: 'Sonnet', haiku: 'Haiku' };
const heavy = (t) => (t?.technique || []).some((x) => /three|webgl|shader/i.test(x));
function modelHint() {
+ if (picks.length > 1) return modelHintMany();
+ const selected = one();
const m = $('#model').value;
const rec = selected ? (heavy(selected) ? 'opus' : 'sonnet') : null;
const recTxt = rec ? `Mẫu này ${heavy(selected) ? 'dựng 3D/shader' : 'là 2D'} → đề xuất ${MODEL_NAME[rec]}.` : 'Chọn mẫu để xem đề xuất.';
@@ -367,6 +449,18 @@
const warn = m === 'haiku' && rec === 'opus' ? ' Haiku hay làm phẳng cảnh 3D, nên dùng Opus.' : m !== 'auto' && rec && m !== rec ? ` (đang chọn ${MODEL_NAME[m]} thay vì đề xuất)` : '';
$('#modelHint').textContent = recTxt + warn + ' Agent ngoài thì model do agent đó quyết.';
}
+ // Nhiều mẫu: "3 mẫu 2D → Sonnet, 1 mẫu 3D/shader → Opus" (mỗi job tự chọn theo mẫu của nó).
+ function modelHintMany() {
+ const m = $('#model').value;
+ const nHeavy = picks.filter(heavy).length, nLight = picks.length - nHeavy;
+ $('#model').querySelector('[value=auto]').textContent = 'Tự chọn theo từng mẫu';
+ const parts = [];
+ if (nLight) parts.push(`${nLight} mẫu 2D → ${MODEL_NAME.sonnet}`);
+ if (nHeavy) parts.push(`${nHeavy} mẫu 3D/shader → ${MODEL_NAME.opus}`);
+ const txt = m === 'auto' ? `Mỗi video tự chọn theo mẫu: ${parts.join(', ')}.`
+ : `Cả ${picks.length} video dùng ${MODEL_NAME[m]} (đề xuất: ${parts.join(', ')}).${m === 'haiku' && nHeavy ? ' Haiku hay làm phẳng cảnh 3D, nên dùng Opus cho mẫu 3D.' : ''}`;
+ $('#modelHint').textContent = txt + ' Agent ngoài thì model do agent đó quyết.';
+ }
$('#model').addEventListener('change', modelHint);
window.addEventListener('lumreels:picked', modelHint);
modelHint();
diff --git a/server/public/index.html b/server/public/index.html
index 7edaff6..da59489 100644
--- a/server/public/index.html
+++ b/server/public/index.html
@@ -37,7 +37,10 @@
<button class="chip" data-cat="viet-nam" role="radio" aria-checked="false">Việt Nam hoá</button>
</div>
<label class="toggle"><input type="checkbox" id="readyOnly" /> Chỉ mẫu dùng được</label>
+ <label class="toggle switch"><input type="checkbox" id="multiPick" role="switch" aria-describedby="multiHint" /> Chọn nhiều mẫu</label>
+ <span class="sr" id="multiHint">Bật lên thì bấm mẫu để chọn hoặc bỏ, tối đa 12 mẫu, mỗi mẫu ra 1 video cùng nội dung.</span>
</div>
+ <p class="pick-note" id="pickNote" role="status" aria-live="polite"></p>
<div id="grid" class="grid" aria-live="polite"></div>
</section>
diff --git a/server/public/style.css b/server/public/style.css
index 57b2f17..521357f 100644
--- a/server/public/style.css
+++ b/server/public/style.css
@@ -156,3 +156,26 @@ dialog a { color: var(--accent); }
.update-banner .ub-text { flex: 1; }
.update-banner .ub-close { background: none; border: 0; color: var(--ink-2); font-size: 22px; line-height: 1; cursor: pointer; padding: 4px 8px; border-radius: 8px; }
.update-banner .ub-close:hover { color: var(--ink); background: var(--line); }
+
+/* ---- chọn nhiều mẫu ---- */
+.toggle.switch { padding: 0 14px 0 6px; border-radius: 999px; border: 1px solid var(--line); background: var(--panel); color: var(--ink); font-weight: 600; }
+.toggle.switch input { appearance: none; -webkit-appearance: none; width: 36px; height: 22px; margin: 0; border-radius: 999px; background: var(--panel-2); border: 1px solid var(--line); position: relative; cursor: pointer; transition: background .15s, border-color .15s; flex: none; }
+.toggle.switch input::after { content: ''; position: absolute; top: 2px; left: 2px; width: 16px; height: 16px; border-radius: 50%; background: var(--ink-3); transition: transform .15s, background .15s; }
+.toggle.switch input:checked { background: var(--accent); border-color: var(--accent); }
+.toggle.switch input:checked::after { transform: translateX(14px); background: var(--accent-ink); }
+.toggle.switch:has(input:checked) { border-color: var(--accent); }
+.pick-note { margin: -4px 0 14px; padding: 8px 12px; font-size: 14px; color: var(--warn); background: rgba(242,201,76,.08); border: 1px solid rgba(242,201,76,.3); border-radius: 8px; }
+.pick-note:empty { display: none; }
+.tpl .order { position: absolute; top: 8px; left: 8px; z-index: 1; min-width: 30px; height: 30px; padding: 0 8px; display: grid; place-items: center; border-radius: 999px; background: var(--accent); color: var(--accent-ink); font: 700 15px/1 var(--mono); box-shadow: 0 4px 12px -4px rgba(255,107,44,.8); animation: pop .18s ease-out; }
+.tpl .order ~ .badge { display: none; }
+@keyframes pop { from { transform: scale(.6); opacity: 0; } to { transform: scale(1); opacity: 1; } }
+.picked.multi { display: block; padding: 12px; }
+.picked .pm-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 10px; }
+.picked .pm-head .mini { min-height: 36px; font-size: 13px; }
+.picked .strip { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 8px; }
+.picked .pk { position: relative; }
+.picked .pk img, .picked .pk .ph { width: 100%; height: auto; aspect-ratio: 9 / 16; object-fit: cover; border-radius: 6px; display: block; background: var(--bg); }
+.picked .pk .n { position: absolute; left: 3px; bottom: 3px; min-width: 18px; height: 18px; padding: 0 4px; border-radius: 999px; background: var(--accent); color: var(--accent-ink); font: 700 11px/18px var(--mono); text-align: center; }
+.picked .pk .rm { position: absolute; top: -8px; right: -8px; width: 28px; height: 28px; border-radius: 50%; border: 1px solid var(--line); background: var(--panel); color: var(--ink); font-size: 16px; line-height: 1; cursor: pointer; display: grid; place-items: center; padding: 0; }
+.picked .pk .rm::before { content: ''; position: absolute; inset: -8px; } /* vùng bấm ≥ 44px */
+.picked .pk .rm:hover { border-color: var(--bad); color: var(--bad); }
diff --git a/server/server.mjs b/server/server.mjs
index b714c76..d18f832 100644
--- a/server/server.mjs
+++ b/server/server.mjs
@@ -6,7 +6,7 @@ import { fileURLToPath } from 'node:url';
import { spawn } from 'node:child_process';
import {
ROOT, JOBS, TEMPLATES, loadCatalog, templateName, hasGuidance, createJob, runJob, renderJob, readJob, listJobs, readLog, markStale,
- dueJobs, resolveMode, submitScene, previewJob,
+ 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';
@@ -184,6 +184,13 @@ function jobView(job, withLog = false) {
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));
+}
+
let rewriteBusy = false;
let rewriteLast = 0;
@@ -220,11 +227,22 @@ const server = http.createServer(async (req, res) => {
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 });
- if (job.status === 'scheduled') { /* bộ hẹn giờ sẽ chạy khi tới giờ */ }
- else if (resolveMode(job.mode) === 'manual') await runJob(job.id); // chỉ chuyển sang waiting_agent
- else enqueueJob(job.id, () => runJob(job.id));
+ 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);