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.

Edit video: sửa theo QA (job kẹt, multipart, upload hỏng, đĩa, khoá, a11y)

Lumtek5ac32744fd64
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 5a3aea9..f9f7a19 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -18,7 +18,11 @@ It depends on the third-party software below. These packages are **not bundled i
| [edge-tts](https://github.com/rany2/edge-tts) | Optional online voice fallback (uses Microsoft's online TTS service) | LGPL-3.0 (package); service subject to Microsoft's terms |
| ffmpeg, Google Chrome | Installed separately by the user | Their own licenses |
| Edit video (`node edit/setup.mjs`, into `edit/.venv`): [faster-whisper](https://github.com/SYSTRAN/faster-whisper), [CTranslate2](https://github.com/OpenNMT/CTranslate2) | Speech to text with word times | MIT |
-| Edit video: [MediaPipe](https://github.com/google-ai-edge/mediapipe), [OpenCV](https://opencv.org), NumPy, Pillow, fontTools, brotli | Face/person detection, frames, drawing, building fonts | Apache-2.0, Apache-2.0, BSD-3-Clause, MIT-CMU, MIT, MIT |
+| Edit video: [MediaPipe](https://github.com/google-ai-edge/mediapipe), NumPy, Pillow, fontTools, brotli | Face/person detection, arrays, drawing, building fonts | Apache-2.0, BSD-3-Clause, MIT-CMU, MIT, MIT |
+| Edit video: [opencv-contrib-python](https://github.com/opencv/opencv-python) | Frames, warps, resizing | Apache-2.0 (OpenCV); the wheel bundles FFmpeg libraries under **LGPL-2.1** and Qt under LGPL-3.0 |
+| Edit video: [PyAV](https://github.com/PyAV-Org/PyAV) (`av`, pulled in by faster-whisper) | Audio decoding for Whisper | BSD-3-Clause; the wheel bundles FFmpeg libraries under **LGPL-2.1+** |
+| Edit video: [ONNX Runtime](https://github.com/microsoft/onnxruntime) (pulled in by faster-whisper) | Voice activity model runtime | MIT |
+| Edit video: [Matplotlib](https://matplotlib.org) (pulled in by MediaPipe) | Not used directly | Matplotlib License (PSF-based, BSD-compatible) |
| Edit video, GPU only: `nvidia-cublas-cu12`, `nvidia-cudnn-cu12` | CUDA libraries for whisper on NVIDIA GPUs | NVIDIA proprietary license (redistribution terms of the CUDA/cuDNN EULA) |
| Edit video model: [Whisper large-v3](https://huggingface.co/Systran/faster-whisper-large-v3) (CTranslate2 conversion of OpenAI Whisper) | Vietnamese transcription | MIT |
| Edit video models: MediaPipe BlazeFace short range, Selfie Segmenter, Selfie Multiclass 256×256, Face Landmarker (fetched into `edit/askeditor/models/`, SHA-256 pinned) | Face and person | Apache-2.0 (model cards) |
diff --git a/cli.mjs b/cli.mjs
index 1f80a79..e9cf921 100644
--- a/cli.mjs
+++ b/cli.mjs
@@ -9,7 +9,7 @@
// node cli.mjs show <jobId>
// node cli.mjs templates [--json]
// node cli.mjs edit <video> --style <id> [--music file] [--content "dặn thêm"] [--names "Lumfin, …"] [--draft] [--llm off] [--json]
-// node cli.mjs edit-revise <editId> "<lời sửa>" · edit-show <editId> · edit-run <editId>
+// node cli.mjs edit-revise <editId> "<lời sửa>" [--file f] · edit-show <editId> · edit-run <editId> · edit-rm <editId>
import fs from 'node:fs';
import path from 'node:path';
import { createJob, runJob, renderJob, runDue, listJobs, readJob, readLog, jobPaths, loadCatalog, hasGuidance, exportOutput } from './generator/jobs.mjs';
@@ -51,9 +51,10 @@ function usage() {
dựng lại video tự quay theo thẻ kiểu edit (edit-styles/<id>.md) → edits/<id>/out.mp4
cắt ngập ngừng/nói lại (LLM), phụ đề tiếng Việt, zoom, reframe 9:16, nhạc tự hạ, sfx, −14 LUFS.
--draft: phụ đề PIL vẽ thẳng (nhanh), mặc định phụ đề HyperFrames. Cài trước: node edit/setup.mjs
- edit-revise <editId> "<lời>" sửa bằng lời ("bỏ 3 giây đầu", "zoom ít lại") rồi render lại, không phân tích lại
+ edit-revise <editId> "<lời>" | --file <f> sửa bằng lời ("bỏ 3 giây đầu", "zoom ít lại") rồi render lại, không phân tích lại
edit-show <editId> [--json] trạng thái, tiến độ, chữ LLM đã sửa, log
- edit-run <editId> chạy 1 edit đã tạo (MCP/REST dùng)`);
+ edit-run <editId> chạy 1 edit đã tạo (MCP/REST dùng)
+ edit-rm <editId> xoá hẳn 1 edit (thư mục edits/<id>)`);
}
const readContent = (c) => (fs.existsSync(c) && fs.statSync(c).isFile() ? fs.readFileSync(c, 'utf8') : c);
@@ -86,10 +87,16 @@ try {
else if (done.error) console.log('Lỗi: ' + done.error);
}
process.exit(done.status === 'error' ? 1 : 0);
- } else if (cmd === 'edit' || cmd === 'edit-run' || cmd === 'edit-revise' || cmd === 'edit-show') {
+ } else if (['edit', 'edit-run', 'edit-revise', 'edit-show', 'edit-rm'].includes(cmd)) {
const E = await import('./edit/jobs.mjs');
const log = opt.json ? () => {} : console.log;
let r;
+ if (cmd === 'edit-rm') {
+ if (!pos[0]) { usage(); process.exit(2); }
+ E.deleteEdit(pos[0]);
+ console.log('đã xoá edit ' + pos[0]);
+ process.exit(0);
+ }
if (cmd === 'edit-show') {
const v = pos[0] && E.editView(pos[0]);
if (!v) { console.error('không thấy edit ' + (pos[0] || '')); process.exit(1); }
@@ -104,7 +111,7 @@ try {
}
if (cmd === 'edit') {
if (!pos[0]) { usage(); process.exit(2); }
- const job = E.createEdit({ video: pos[0], style: typeof opt.style === 'string' ? opt.style : 'sach-gon', music: typeof opt.music === 'string' ? opt.music : undefined,
+ const job = await E.createEdit({ video: pos[0], style: typeof opt.style === 'string' ? opt.style : 'sach-gon', music: typeof opt.music === 'string' ? opt.music : undefined,
content: typeof opt.content === 'string' ? readContent(opt.content) : undefined, names: typeof opt.names === 'string' ? opt.names : undefined,
draft: !!opt.draft, llm: opt.llm === 'off' ? 'off' : 'on' });
r = await E.runEditJob(job.id, { log });
@@ -112,8 +119,10 @@ try {
if (!pos[0]) { usage(); process.exit(2); }
r = await E.runEditJob(pos[0], { log });
} else {
- if (!pos[0] || !pos[1]) { usage(); process.exit(2); }
- r = await E.reviseEditJob(pos[0], pos.slice(1).join(' '), { log });
+ // lời sửa: đối số, hoặc --file <đường dẫn> (MCP dùng: lời bắt đầu bằng "--" không bị hiểu nhầm thành cờ)
+ const text = typeof opt.file === 'string' ? fs.readFileSync(opt.file, 'utf8') : pos.slice(1).join(' ');
+ if (!pos[0] || !text.trim()) { usage(); process.exit(2); }
+ r = await E.reviseEditJob(pos[0], text, { log });
}
if (opt.json) out(E.editView(r.id));
else console.log(r.ok ? [`edit: ${r.id}`, `MP4: ${r.out}`, `EDL: ${r.edl}`, `Xem trước: ${path.join(r.dir, 'preview.jpg')}`].join('\n') : 'Lỗi: ' + r.error);
diff --git a/docs/CHI-TIET.md b/docs/CHI-TIET.md
index 0a51201..8eacdf0 100644
--- a/docs/CHI-TIET.md
+++ b/docs/CHI-TIET.md
@@ -62,7 +62,7 @@ video ─ edit/ingest.mjs : ffprobe đủ (xoay, VFR, HDR, start_time) + SHA-2
khoảng lặng, mặt (BlazeFace) → analysis.json
─ edit/planner.mjs : Claude (Sonnet, không tool, `--tools ""`) đọc lời chép đánh số + thẻ kiểu → ĐỀ XUẤT NGỮ NGHĨA
(bỏ khoảng chữ nào, chữ nhấn, zoom/sfx ở chữ nào, sửa chính tả). Code kiểm; sai → LLM sửa 1 vòng;
- vẫn sai → bỏ mục hỏng. Code dựng EDL: biên cắt (+0,18 s sau chữ, −0,10 s trước chữ), rút lặng,
+ vẫn sai → bỏ mục hỏng. Code dựng EDL: biên cắt (+0,22 s sau chữ vì whisper hay báo hết chữ sớm, −0,10 s trước chữ), rút lặng,
mật độ zoom, sfx theo zoom → edl.json (kiểm bằng edit/edl.mjs)
─ lumedit stills : preview.jpg (lưới 16 khung, phụ đề nháp)
─ lumedit render : 1 lượt: Timeline (đoạn giữ, tiếng gốc nối crossfade 20 ms) + Framing (cửa sổ 9:16 theo mặt) + zoom
@@ -78,10 +78,13 @@ video ─ edit/ingest.mjs : ffprobe đủ (xoay, VFR, HDR, start_time) + SHA-2
- Clip thử tổng hợp (khi chưa có clip người thật): `node edit/test/make-synth.mjs edits/_synth/synth.mp4 [--wide]` (nối hình + giọng sạch của vài job, chèn 1 khoảng lặng 1,6 s và 1 câu nói dở rồi nói lại; ghi kèm `.truth.json`).
- **Giao diện**: tab "Edit video của bạn" cạnh "Dựng từ mẫu": kéo thả video (≤ 2 GB), chọn kiểu, nhạc (tổng hợp có sẵn hoặc tải file), ô "tên riêng" (AI dùng để sửa chữ máy nghe sai, ngoài các tên này chỉ sửa chữ vô nghĩa rõ ràng), ô dặn thêm, bản nháp; thanh tiến độ theo 9 bước, video ra, **danh sách chữ AI đã sửa** để người xem lại, ô sửa bằng lời + nút Render lại, các lần sửa, nhật ký. Chưa cài `edit/setup.mjs` thì tab hiện lệnh cài.
- **REST** (`edit/http.mjs`, cùng chống DNS rebinding qua Host như các route khác, thêm chặn `Origin` lạ cho lệnh ghi):
- `GET /api/edit-options` (đã cài chưa, kiểu edit, nhạc) · `GET /api/edits` · `POST /api/edits` multipart (`video` ≤ 2 GB, `music`?, `style`, `musicStyle`?, `content`?, `names`?, `draft`?; ghi thẳng ra `edits/<id>/source.*`, không giữ trong RAM) hoặc JSON `{path, style, music?, content?, names?, draft?}` khi gọi từ máy · `GET /api/edits/:id` (trạng thái, bước, %, log, `fixes`, `revisions`, `checks`) · `POST /api/edits/:id/revise {instruction}` · file `/edits/:id/(out.mp4|preview.jpg|preview-final.jpg|edl.json|versions/out-<n>.mp4)`.
-- **Hàng chờ**: mỗi lúc 1 edit chạy trên cả máy (khoá `edits/.edit.lock` có pid, dùng chung cho server, CLI, MCP; tiến trình chết thì khoá tự hết). Hồ sơ `edits/<id>/job.json`: `queued → running → done | error`, `step/pct`. Server khởi động: edit chạy dở bị đánh dấu lỗi để bấm lại.
-- **Sửa bằng lời** (`reviseEdit`): LLM đọc lời chép kèm mốc giây BẢN HIỆN TẠI + đề xuất hiện tại → trả đề xuất mới, `cut_output` (giây bản hiện tại, code đổi sang giây nguồn theo keep và nới mép cho trọn chữ) và núm kiểu (`zoomScale`, `zoomMinGap`, `captionsMaxWords`, `musicGainDb`, `pause`, `sfxOff`). Code dựng lại EDL, render từ bước "xem trước". Bản cũ giữ ở `versions/out-<n>.mp4` + `edl-<n>.json`; trạng thái sửa trong `state.json`. LLM sai 2 vòng → báo lỗi, bản cũ giữ nguyên.
-- **CLI**: `node cli.mjs edit <video> … [--names "Lumfin, …"]`, `edit-revise <id> "<lời>"`, `edit-show <id> [--json]`, `edit-run <id>`. **MCP**: `edit_video {path, style, music?, notes?, names?, draft?}` (chạy nền, trả editId), `revise_edit {editId, instruction}`, `get_edit {editId?}`.
+ `GET /api/edit-options` (đã cài chưa, kiểu edit, nhạc) · `GET /api/edits` · `POST /api/edits` multipart (`video` ≤ 2 GB, `music`?, `style`, `musicStyle`?, `content`?, `names`?, `draft`?; ghi thẳng ra `edits/<id>/source.*`, không giữ trong RAM) hoặc JSON `{path, style, music?, content?, names?, draft?}` khi gọi từ máy · `GET /api/edits/:id` (trạng thái, bước, %, log, `fixes`, `revisions`, `checks`) · `POST /api/edits/:id/revise {instruction}` · `DELETE /api/edits/:id` (xoá hẳn; đang chạy → 409) · file `/edits/:id/(out.mp4|out-r<n>.mp4|preview.jpg|preview-final.jpg|edl.json)`.
+ Upload: phải có `Content-Length`, ổ đĩa phải trống ≥ 5× cỡ upload (507 nếu không), mỗi lúc nhận 1 upload (429), bộ đệm multipart luôn ≤ 64 KB + 1 chunk (trước dấu phân cách đầu, đầu phần, trường chữ, sau dấu kết thúc; quá thì 400 và đóng kết nối); lỗi nào sau khi đã ghi file cũng xoá cả thư mục `edits/<id>`. Video và nhạc được ffprobe ngay khi tạo (không có hình/tiếng, < 1 s, > 30 phút → 422) trước khi chạy whisper/LLM.
+- **Hàng chờ**: mỗi lúc 1 edit chạy trên cả máy (khoá `edits/.edit.lock` tạo độc quyền `wx`, có pid; khoá của tiến trình đã chết được gỡ dưới khoá phụ `.edit.lock.break` cũng `wx`, nên 2 tiến trình không thể cùng gỡ/cùng giữ). Hồ sơ `edits/<id>/job.json`: `queued → running → done | error`, `step/pct`. Mỗi lần đọc job (UI, REST, MCP, CLI): job `queued/running` mà pid đã chết → tự chuyển `error` (dựng lần đầu) hoặc `done` + `reviseError` (lần sửa), kèm lý do.
+- **Dọn đĩa**: xong mỗi lượt (được hay lỗi) xoá `proxy.mov`, `base.mp4`, `captions.webm`, `captions/lib`, `audio/`; giữ nguồn, `edl.json`, `out*.mp4`, `captions/index.html`, log và các JSON nhỏ (phân tích, chép lời, mặt). Sửa bằng lời dựng lại proxy từ nguồn (~5 s; cùng thông số nên ra đúng file cũ, cache chữ/mặt dùng lại). Xoá hẳn: nút "Xoá bản dựng này" trên UI, `DELETE /api/edits/:id`, `node cli.mjs edit-rm <id>`.
+- **Đã cài chưa** (`setupStatus`): python trong venv + dấu `edit/.venv/.lumedit-ready.json` do setup ghi sau khi import thử đủ gói, kèm danh sách file phải còn (model whisper, model mặt/người, font). Thiếu gì UI/REST/MCP báo đúng cái thiếu.
+- **Sửa bằng lời** (`reviseEdit`): LLM đọc lời chép kèm mốc giây BẢN HIỆN TẠI + đề xuất hiện tại → trả đề xuất mới, `cut_output` (giây bản hiện tại, code đổi sang giây nguồn theo keep và nới mép cho trọn chữ) và núm kiểu (`zoomScale`, `zoomMinGap`, `captionsMaxWords`, `musicGainDb`, `pause`, `sfxOff`). Code dựng lại EDL, render từ bước "xem trước". Mỗi lần sửa n ra file MỚI `out-r<n>.mp4` (Windows khoá file đang phát nên không ghi đè), bản trước giữ nguyên; EDL trước lần sửa n ở `versions/edl-<n>.json`; `state.json.out` = bản mới nhất. Lỗi giữa chừng → trả `edl.json` về bản trước. LLM sai 2 vòng → báo lỗi, bản cũ giữ nguyên.
+- **CLI**: `node cli.mjs edit <video> … [--names "Lumfin, …"]`, `edit-revise <id> "<lời>"` (hoặc `--file <f>`: MCP truyền lời sửa qua file, không qua argv), `edit-rm <id>`, `edit-show <id> [--json]`, `edit-run <id>`. **MCP**: `edit_video {path, style, music?, notes?, names?, draft?}` (chạy nền, trả editId), `revise_edit {editId, instruction}`, `get_edit {editId?}`.
- **Phụ đề không chồng nhau**: luật thời gian nhóm chữ (giống nhau ở `captions-hf.mjs` và `lumedit.py`): nối khe < 0,4 s, tối thiểu 0,25 s nhưng không bao giờ quá điểm bắt đầu của nhóm sau, nhóm bị ép < 0,1 s gộp vào nhóm sau; kiểm `cardOverlaps` — có chồng là dừng. (Lỗi cũ: chữ nói nhanh 0,22 s bị kéo lên 0,25 s nên "TRÀ" đè "SỮA".)
- **Tốc độ phụ đề HyperFrames** (đo trên 23,8 s, 80 nhóm): 1080p 61 s; `-w 10` 59 s; dựng ở 720p rồi phóng 51 s / 47 s (chữ mờ hơn, chưa dùng). Hướng tăng tốc thật (để sau): chỉ chụp khung có chuyển động (0,2 s đầu mỗi nhóm + khung đổi màu), giữ các khung tĩnh bằng ffmpeg.
- Giới hạn: 1 người nói, tiếng Việt; footage có nhạc nền to làm bước nghe lại loại nhiều chữ; reframe từ 1080p ngang phóng cửa sổ 608×1080 lên 1080×1920 (mờ hơn).
diff --git a/edit/env.mjs b/edit/env.mjs
index 977befc..bbb5732 100644
--- a/edit/env.mjs
+++ b/edit/env.mjs
@@ -19,7 +19,21 @@ export function venvPython() {
return process.platform === 'win32' ? win : nix;
}
-export function venvReady() { return fs.existsSync(venvPython()); }
+export const READY_MARK = path.join(VENV, '.lumedit-ready.json');
+/**
+ * Đã cài đủ chưa: python trong venv + dấu READY của setup + các file nó ghi nhận (model whisper, model mặt/người,
+ * font) vẫn còn. Trả {ready, missing[]}. Gói Python được setup kiểm bằng import trước khi ghi dấu.
+ */
+export function setupStatus() {
+ const missing = [];
+ if (!fs.existsSync(venvPython())) missing.push('môi trường Python edit/.venv');
+ let mark = null;
+ try { mark = JSON.parse(fs.readFileSync(READY_MARK, 'utf8')); } catch { /* chưa có */ }
+ if (!mark) missing.push('dấu cài xong (chạy lại setup)');
+ else for (const f of mark.files || []) if (!fs.existsSync(f)) missing.push(path.basename(path.dirname(f)) + '/' + path.basename(f));
+ return { ready: missing.length === 0, missing };
+}
+export function venvReady() { return setupStatus().ready; }
/** Thư mục chứa thư viện CUDA của wheel nvidia-* trong venv (Linux cần LD_LIBRARY_PATH trước khi Python chạy). */
function cudaLibDirs() {
diff --git a/edit/http.mjs b/edit/http.mjs
index 950f921..2f4ba05 100644
--- a/edit/http.mjs
+++ b/edit/http.mjs
@@ -1,54 +1,67 @@
// REST cho Edit video (server/server.mjs gọi handleEditRoute). Chống DNS rebinding đã làm ở server (Host),
-// ở đây chặn thêm Origin lạ cho mọi lệnh ghi (trang web khác không gửi form upload/đường dẫn vào được).
-// GET /api/edit-options → {ready, setup, styles[], music[]}
-// GET /api/edits → danh sách
-// POST /api/edits → multipart (video ≤ 2 GB, music?, style, musicStyle?, content?, names?, draft?)
+// ở đây chặn thêm Origin lạ cho mọi lệnh ghi (trang web khác không gửi form upload/đường dẫn/xoá vào được).
+// GET /api/edit-options → {ready, missing, setup, styles[], music[], maxUploadBytes}
+// GET /api/edits → danh sách
+// POST /api/edits → multipart (video ≤ 2 GB, music?, style, musicStyle?, content?, names?, draft?)
// hoặc JSON {path, style, music?(đường dẫn|tên nhạc tổng hợp), content?, names?, draft?}
-// GET /api/edits/:id → trạng thái, tiến độ, log, chữ LLM đã sửa, các lần sửa
-// POST /api/edits/:id/revise → {instruction}: LLM sửa EDL theo lời, render lại, không phân tích lại
-// GET /edits/:id/(out.mp4|out-r<n>.mp4|preview.jpg|preview-final.jpg|edl.json)
+// GET /api/edits/:id → trạng thái, tiến độ, log, chữ LLM đã sửa, các lần sửa
+// POST /api/edits/:id/revise → {instruction}: LLM sửa EDL theo lời, render lại, không phân tích lại
+// DELETE /api/edits/:id → xoá hẳn thư mục edits/<id>
+// GET /edits/:id/(out.mp4|out-r<n>.mp4|preview.jpg|preview-final.jpg|edl.json)
import fs from 'node:fs';
import path from 'node:path';
import { MUSIC_LIST, MUSIC_STYLES, writeMusic } from '../engine/audio/music.mjs';
import {
- ID_RE, editDir, newEditId, createEdit, runEditJob, reviseEditJob, editView, listEdits, editStyles, editReady, readEditJob, markStaleEdits,
+ ID_RE, EDITS, editDir, newEditId, createEdit, runEditJob, reviseEditJob, editView, listEdits, editStyles, editReady, readEditJob,
+ markStaleEdits, deleteEdit,
} from './jobs.mjs';
export const MAX_UPLOAD = 2 * 1024 ** 3; // 2 GB
+const MAX_BODY = MAX_UPLOAD + 200 * 1024 ** 2; // + nhạc + trường chữ
+const DISK_FACTOR = 5; // cần trống ≥ 5× cỡ upload (nguồn + proxy + nền + bản ra + dự phòng)
+const SMALL = 64 * 1024; // bộ đệm tối đa trước dấu phân cách đầu / sau dấu kết thúc / trường chữ
const VIDEO_EXT = new Set(['.mp4', '.mov', '.m4v', '.mkv', '.webm', '.avi', '.3gp']);
const AUDIO_EXT = new Set(['.mp3', '.wav', '.m4a', '.aac', '.ogg', '.flac', '.opus']);
+const httpErr = (code, msg) => Object.assign(new Error(msg), { code });
export function initEdits() { markStaleEdits(); }
/** Nhạc tổng hợp có sẵn → file wav 60 s trong thư mục edit (lặp khi video dài hơn). */
function synthMusicFile(id, styleName) {
- if (!MUSIC_STYLES.includes(styleName)) throw new Error('không có nhạc tổng hợp "' + styleName + '"');
+ if (!MUSIC_STYLES.includes(styleName)) throw httpErr(400, 'không có nhạc tổng hợp "' + styleName + '"');
const f = path.join(editDir(id), `music-${styleName}.wav`);
if (!fs.existsSync(f)) writeMusic(styleName, f, 60, 1);
return f;
}
/**
- * Đọc multipart/form-data theo luồng (không giữ file trong RAM). Trường text ≤ 64 KB; file ghi thẳng ra đĩa qua
- * fileTarget(field, filename) → đường dẫn | null (null = bỏ qua). Tổng ≤ maxBytes.
+ * Đọc multipart/form-data theo luồng (file ghi thẳng ra đĩa, không giữ trong RAM).
+ * Bộ đệm luôn nhỏ: trước dấu phân cách đầu ≤ 64 KB, đầu mỗi phần ≤ 16 KB, trường chữ ≤ 64 KB, sau dấu kết thúc ≤ 64 KB;
+ * trong thân file chỉ giữ lại đuôi đủ dài để bắt dấu phân cách bị cắt ngang 2 chunk (không nối dồn → chi phí tuyến tính).
+ * fileTarget(field, filename) → đường dẫn | null (bỏ qua) | throw (từ chối). Tổng ≤ maxBytes.
*/
export function parseMultipart(req, { maxBytes, fileTarget }) {
return new Promise((resolve, reject) => {
const m = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(req.headers['content-type'] || '');
- if (!m) return reject(Object.assign(new Error('thiếu boundary multipart'), { code: 400 }));
+ if (!m) return reject(httpErr(400, 'thiếu boundary multipart'));
const delim = Buffer.from('\r\n--' + (m[1] || m[2]).trim());
- const fields = {}; const files = {};
+ const fields = {}; const files = {}; const opened = [];
let buf = Buffer.from('\r\n'); // để dấu phân cách đầu tiên giống mọi dấu sau
- let state = 'pre'; let total = 0; let cur = null; let failed = false;
- const fail = (e) => { if (failed) return; failed = true; cur?.stream?.destroy(); req.unpipe?.(); req.resume(); reject(e); };
+ let state = 'pre'; let total = 0; let epilogue = 0; let cur = null; let failed = false;
+ const fail = (e) => {
+ if (failed) return; failed = true;
+ for (const s of opened) s.destroy();
+ req.pause();
+ reject(e.code ? e : httpErr(400, e.message));
+ };
const write = (data) => {
if (!cur || !data.length) return;
- if (cur.stream) { cur.size += data.length; if (!cur.stream.write(data)) { req.pause(); cur.stream.once('drain', () => req.resume()); } }
- else if (cur.text !== null) { cur.text += data.toString('utf8'); if (cur.text.length > 64 * 1024) fail(Object.assign(new Error(`trường ${cur.name} quá dài`), { code: 413 })); }
+ if (cur.stream) { cur.size += data.length; if (!cur.stream.write(data)) { req.pause(); cur.stream.once('drain', () => { if (!failed) req.resume(); }); } }
+ else if (cur.text !== null) { cur.text += data.toString('utf8'); if (cur.text.length > SMALL) throw httpErr(413, `trường ${cur.name} quá dài`); }
};
const closePart = () => {
if (!cur) return;
- if (cur.stream) { cur.stream.end(); files[cur.name] = { path: cur.path, filename: cur.filename, size: cur.size, done: new Promise((r) => cur.stream.on('close', r)) }; }
+ if (cur.stream) { const s = cur.stream; s.end(); files[cur.name] = { path: cur.path, filename: cur.filename, size: cur.size, done: new Promise((r) => s.on('close', r)) }; }
else if (cur.text !== null) fields[cur.name] = cur.text;
cur = null;
};
@@ -58,25 +71,27 @@ export function parseMultipart(req, { maxBytes, fileTarget }) {
const i = buf.indexOf(delim);
if (i < 0) {
const keep = delim.length + 4;
- if (state === 'body' && buf.length > keep) { write(buf.subarray(0, buf.length - keep)); buf = buf.subarray(buf.length - keep); }
+ if (state === 'pre') { if (buf.length > SMALL) throw httpErr(400, 'không thấy dấu phân cách multipart trong 64 KB đầu'); return; }
+ if (buf.length > keep) { write(buf.subarray(0, buf.length - keep)); buf = Buffer.from(buf.subarray(buf.length - keep)); }
return;
}
if (state === 'body') write(buf.subarray(0, i));
closePart();
- if (buf.length < i + delim.length + 2) { buf = buf.subarray(i); state = 'pre'; return; }
+ if (buf.length < i + delim.length + 2) { buf = Buffer.from(buf.subarray(i)); state = 'pre'; return; }
const tail = buf.subarray(i + delim.length, i + delim.length + 2).toString();
- if (tail === '--') { state = 'end'; buf = Buffer.alloc(0); return; }
+ if (tail === '--') { state = 'end'; epilogue = buf.length - (i + delim.length + 2); buf = Buffer.alloc(0); if (epilogue > SMALL) throw httpErr(400, 'dữ liệu thừa sau multipart'); return; }
buf = buf.subarray(i + delim.length + 2); state = 'head';
} else if (state === 'head') {
const j = buf.indexOf('\r\n\r\n');
- if (j < 0) { if (buf.length > 16 * 1024) fail(Object.assign(new Error('đầu phần multipart quá dài'), { code: 400 })); return; }
+ if (j < 0) { if (buf.length > 16 * 1024) throw httpErr(400, 'đầu phần multipart quá dài'); return; }
const head = buf.subarray(0, j).toString('utf8'); buf = buf.subarray(j + 4);
const name = /name="([^"]*)"/i.exec(head)?.[1] || '';
const filename = /filename="([^"]*)"/i.exec(head)?.[1];
cur = { name, filename, text: null, stream: null, size: 0 };
if (filename !== undefined) {
+ if (files[name]) throw httpErr(400, `trường ${name} gửi 2 lần`);
const target = filename ? fileTarget(name, filename) : null;
- if (target) { cur.path = target; cur.stream = fs.createWriteStream(target); cur.stream.on('error', fail); }
+ if (target) { cur.path = target; cur.stream = fs.createWriteStream(target); opened.push(cur.stream); cur.stream.on('error', fail); }
} else cur.text = '';
state = 'body';
} else return;
@@ -85,16 +100,20 @@ export function parseMultipart(req, { maxBytes, fileTarget }) {
req.on('data', (chunk) => {
if (failed) return;
total += chunk.length;
- if (total > maxBytes) return fail(Object.assign(new Error(`file quá lớn (tối đa ${Math.round(maxBytes / 1024 ** 3)} GB)`), { code: 413 }));
- buf = buf.length ? Buffer.concat([buf, chunk]) : chunk;
- try { pump(); } catch (e) { fail(e); }
+ try {
+ if (total > maxBytes) throw httpErr(413, `file quá lớn (tối đa ${Math.round(MAX_UPLOAD / 1024 ** 3)} GB)`);
+ if (state === 'end') { epilogue += chunk.length; if (epilogue > SMALL) throw httpErr(400, 'dữ liệu thừa sau multipart'); return; }
+ buf = buf.length ? Buffer.concat([buf, chunk]) : chunk; // buf ≤ 64 KB + chunk ở mọi trạng thái
+ pump();
+ } catch (e) { fail(e); }
});
req.on('end', async () => {
if (failed) return;
- if (state !== 'end') return fail(Object.assign(new Error('multipart bị cắt ngang'), { code: 400 }));
+ if (state !== 'end') return fail(httpErr(400, 'multipart bị cắt ngang'));
await Promise.all(Object.values(files).map((f) => f.done));
resolve({ fields, files });
});
+ req.on('aborted', () => fail(httpErr(400, 'tải lên bị ngắt')));
req.on('error', fail);
});
}
@@ -105,11 +124,23 @@ const originOk = (req, allowedHosts) => {
try { return allowedHosts.has(new URL(o).host.toLowerCase()); } catch { return false; }
};
+/** Trả lỗi rồi đóng kết nối (không đọc nốt phần thân còn lại của upload hỏng). */
+function sendAndClose(res, req, send, code, body) {
+ res.setHeader('Connection', 'close');
+ res.on('finish', () => req.destroy());
+ send(res, code, body);
+}
+
+function freeBytes(dir) {
+ try { const s = fs.statfsSync(dir); return Number(s.bavail) * Number(s.bsize); } catch { return Infinity; }
+}
+
+let uploading = false; // một lúc chỉ nhận 1 upload
+
/** Trả true nếu đã xử lý route. */
export async function handleEditRoute(req, res, p, { send, readBody, serveFile, allowedHosts }) {
- const isWrite = req.method === 'POST';
if (!p.startsWith('/api/edit') && !p.startsWith('/edits/')) return false;
- if (isWrite && !originOk(req, allowedHosts)) { send(res, 403, { error: 'origin không hợp lệ' }); return true; }
+ if (['POST', 'DELETE', 'PUT', 'PATCH'].includes(req.method) && !originOk(req, allowedHosts)) { sendAndClose(res, req, send, 403, { error: 'origin không hợp lệ' }); return true; }
if (p === '/api/edit-options' && req.method === 'GET') {
send(res, 200, { ...editReady(), styles: editStyles(), music: MUSIC_LIST.map((m) => ({ id: m.name, desc: m.desc })), maxUploadBytes: MAX_UPLOAD });
@@ -117,47 +148,69 @@ export async function handleEditRoute(req, res, p, { send, readBody, serveFile,
}
if (p === '/api/edits' && req.method === 'GET') { send(res, 200, listEdits()); return true; }
if (p === '/api/edits' && req.method === 'POST') {
- if (!editReady().ready) { send(res, 503, { error: editReady().note }); return true; }
+ const ready = editReady();
+ if (!ready.ready) { sendAndClose(res, req, send, 503, { error: ready.note }); return true; }
const ct = String(req.headers['content-type'] || '');
- let input;
if (/^multipart\/form-data/i.test(ct)) {
+ const len = Number(req.headers['content-length']);
+ if (!Number.isFinite(len) || len <= 0) { sendAndClose(res, req, send, 411, { error: 'cần Content-Length (trình duyệt tự gửi)' }); return true; }
+ if (len > MAX_BODY) { sendAndClose(res, req, send, 413, { error: 'file quá lớn (tối đa 2 GB)' }); return true; }
+ fs.mkdirSync(EDITS, { recursive: true });
+ const free = freeBytes(EDITS);
+ if (free < DISK_FACTOR * len) {
+ sendAndClose(res, req, send, 507, { error: `ổ đĩa còn ${(free / 1e9).toFixed(1)} GB, cần ≥ ${((DISK_FACTOR * len) / 1e9).toFixed(1)} GB (5× cỡ video) để dựng` });
+ return true;
+ }
+ if (uploading) { sendAndClose(res, req, send, 429, { error: 'đang nhận 1 video khác, chờ tải xong rồi gửi tiếp' }); return true; }
+ uploading = true;
const id = newEditId();
- fs.mkdirSync(editDir(id), { recursive: true });
- let parsed;
+ const dir = editDir(id);
try {
- parsed = await parseMultipart(req, {
- maxBytes: MAX_UPLOAD + 200 * 1024 ** 2,
+ fs.mkdirSync(dir, { recursive: true });
+ const { fields, files } = await parseMultipart(req, {
+ maxBytes: MAX_BODY,
fileTarget: (field, filename) => {
const ext = path.extname(filename).toLowerCase();
- if (field === 'video') { if (!VIDEO_EXT.has(ext)) throw Object.assign(new Error(`định dạng video ${ext || '?'} chưa hỗ trợ`), { code: 415 }); return path.join(editDir(id), 'source' + ext); }
- if (field === 'music') { if (!AUDIO_EXT.has(ext)) throw Object.assign(new Error(`định dạng nhạc ${ext || '?'} chưa hỗ trợ`), { code: 415 }); return path.join(editDir(id), 'music' + ext); }
+ if (field === 'video') { if (!VIDEO_EXT.has(ext)) throw httpErr(415, `định dạng video ${ext || '?'} chưa hỗ trợ`); return path.join(dir, 'source' + ext); }
+ if (field === 'music') { if (!AUDIO_EXT.has(ext)) throw httpErr(415, `định dạng nhạc ${ext || '?'} chưa hỗ trợ`); return path.join(dir, 'music' + ext); }
return null;
},
});
+ uploading = false;
+ if (!files.video?.size) throw httpErr(400, 'thiếu file video');
+ let music = files.music?.size ? files.music.path : null;
+ if (!music && fields.musicStyle && fields.musicStyle !== 'none') music = synthMusicFile(id, fields.musicStyle);
+ const job = await createEdit({
+ id, video: files.video.path, sourceName: files.video.filename, style: fields.style, music,
+ musicName: files.music?.filename || (fields.musicStyle && fields.musicStyle !== 'none' ? `nhạc tổng hợp ${fields.musicStyle}` : null),
+ content: fields.content, names: fields.names, draft: fields.draft === '1' || fields.draft === 'true',
+ });
+ runEditJob(job.id).catch((e) => console.error('[edit]', job.id, e.message));
+ send(res, 202, editView(job.id));
} catch (e) {
- fs.rmSync(editDir(id), { recursive: true, force: true });
- send(res, e.code && Number.isInteger(e.code) ? e.code : 400, { error: e.message });
- return true;
+ uploading = false;
+ try { fs.rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }); } catch (err) { console.error("[edit] không xoá được", dir, err.message); } // không để source.* mồ côi
+ const code = Number.isInteger(e.code) ? e.code : 422;
+ if (res.headersSent) return true;
+ if (req.complete) send(res, code, { error: e.message }); else sendAndClose(res, req, send, code, { error: e.message });
}
- const { fields, files } = parsed;
- if (!files.video?.size) { fs.rmSync(editDir(id), { recursive: true, force: true }); send(res, 400, { error: 'thiếu file video' }); return true; }
- let music = files.music?.size ? files.music.path : null;
- if (!music && fields.musicStyle && fields.musicStyle !== 'none') music = synthMusicFile(id, fields.musicStyle);
- input = { id, video: files.video.path, sourceName: files.video.filename, style: fields.style, music, musicName: files.music?.filename || (fields.musicStyle && fields.musicStyle !== 'none' ? `nhạc tổng hợp ${fields.musicStyle}` : null),
- content: fields.content, names: fields.names, draft: fields.draft === '1' || fields.draft === 'true' };
- } else {
- const body = await readBody(req, 32 * 1024);
- if (!body.path) { send(res, 400, { error: 'cần multipart (video) hoặc JSON {path}' }); return true; }
- const id = newEditId();
+ return true;
+ }
+ // JSON {path}: gọi từ máy (agent, script)
+ const body = await readBody(req, 32 * 1024);
+ if (!body.path) { send(res, 400, { error: 'cần multipart (video) hoặc JSON {path}' }); return true; }
+ const id = newEditId();
+ try {
let music = null; let musicName = null;
if (body.music && MUSIC_STYLES.includes(body.music)) { fs.mkdirSync(editDir(id), { recursive: true }); music = synthMusicFile(id, body.music); musicName = `nhạc tổng hợp ${body.music}`; }
else if (body.music && body.music !== 'none') music = body.music;
- input = { id, video: body.path, style: body.style, music, musicName, content: body.content ?? body.notes, names: body.names, draft: !!body.draft, llm: body.llm };
+ const job = await createEdit({ id, video: body.path, style: body.style, music, musicName, content: body.content ?? body.notes, names: body.names, draft: !!body.draft, llm: body.llm });
+ runEditJob(job.id).catch((e) => console.error('[edit]', job.id, e.message));
+ send(res, 202, editView(job.id));
+ } catch (e) {
+ try { fs.rmSync(editDir(id), { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }); } catch { /* bỏ qua */ }
+ send(res, Number.isInteger(e.code) ? e.code : 422, { error: e.message });
}
- let job;
- try { job = createEdit(input); } catch (e) { send(res, 422, { error: e.message }); return true; }
- runEditJob(job.id).catch((e) => console.error('[edit]', job.id, e.message));
- send(res, 202, editView(job.id));
return true;
}
let m = /^\/api\/edits\/([\w-]+)$/.exec(p);
@@ -166,21 +219,20 @@ export async function handleEditRoute(req, res, p, { send, readBody, serveFile,
send(res, v ? 200 : 404, v || { error: 'không thấy edit' });
return true;
}
+ if (m && req.method === 'DELETE') {
+ try { deleteEdit(m[1]); send(res, 200, { ok: true, id: m[1] }); }
+ catch (e) { send(res, Number.isInteger(e.code) ? e.code : /không thấy/.test(e.message) ? 404 : 400, { error: e.message }); }
+ return true;
+ }
m = /^\/api\/edits\/([\w-]+)\/revise$/.exec(p);
if (m && req.method === 'POST') {
- const job = ID_RE.test(m[1]) && readEditJob(m[1]);
- if (!job) { send(res, 404, { error: 'không thấy edit' }); return true; }
- if (['queued', 'running'].includes(job.status)) { send(res, 409, { error: 'edit này đang chạy, chờ xong rồi sửa' }); return true; }
- if (!fs.existsSync(path.join(editDir(job.id), 'state.json'))) { send(res, 409, { error: 'edit này chưa dựng xong lần đầu' }); return true; }
const body = await readBody(req, 16 * 1024);
- const text = String(body.instruction || '').trim();
- if (!text) { send(res, 400, { error: 'thiếu lời sửa (instruction)' }); return true; }
- if (text.length > 1000) { send(res, 413, { error: 'lời sửa quá dài (tối đa 1000 ký tự)' }); return true; }
try {
- reviseEditJob(job.id, text).catch((e) => console.error('[edit revise]', job.id, e.message));
- } catch (e) { send(res, 422, { error: e.message }); return true; }
- await new Promise((r) => setTimeout(r, 50));
- send(res, 202, editView(job.id));
+ if (!ID_RE.test(m[1]) || !readEditJob(m[1])) throw httpErr(404, 'không thấy edit');
+ // kiểm đầu vào đồng bộ (throw → 4xx); phần chạy nền có .catch riêng
+ reviseEditJob(m[1], body.instruction).catch((e) => console.error('[edit revise]', m[1], e.message));
+ send(res, 202, editView(m[1]));
+ } catch (e) { send(res, Number.isInteger(e.code) ? e.code : 422, { error: e.message }); }
return true;
}
if (p.startsWith('/api/')) return false;
diff --git a/edit/jobs.mjs b/edit/jobs.mjs
index 72b23e2..9351a27 100644
--- a/edit/jobs.mjs
+++ b/edit/jobs.mjs
@@ -1,18 +1,21 @@
-// Việc Edit video dùng chung cho REST (server), MCP và CLI: hồ sơ edits/<id>/job.json, tiến độ, hàng chờ.
-// Mỗi lúc chỉ 1 edit chạy trên cả máy (khoá file edits/.edit.lock, có pid; tiến trình chết thì khoá tự hết hạn),
-// vì render + whisper + HyperFrames đều ăn GPU/CPU.
+// Việc Edit video dùng chung cho REST (server), MCP và CLI: hồ sơ edits/<id>/job.json, tiến độ, hàng chờ, dọn đĩa.
+// Mỗi lúc chỉ 1 edit chạy trên cả máy (khoá file edits/.edit.lock tạo độc quyền "wx", có pid; khoá của tiến trình
+// đã chết được gỡ dưới một khoá phụ cũng "wx" nên hai tiến trình không thể cùng gỡ/cùng giữ).
import fs from 'node:fs';
import path from 'node:path';
import { EDITS, editDir, newEditId, editVideo, reviseEdit, STEPS } from './pipeline.mjs';
import { listStyles, loadStyle, parseNames } from './planner.mjs';
-import { venvReady } from './env.mjs';
+import { setupStatus } from './env.mjs';
+import { probeSource } from './ingest.mjs';
export { STEPS, EDITS, newEditId, editDir };
export const ID_RE = /^[\w-]{1,80}$/;
const LOCK = path.join(EDITS, '.edit.lock');
+const BREAKER = path.join(EDITS, '.edit.lock.break');
const readJson = (f, d = null) => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return d; } };
-const pidAlive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
+export const pidAlive = (pid) => { if (!Number.isInteger(pid) || pid <= 0) return false; try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
const jobFile = (id) => path.join(editDir(id), 'job.json');
+
/** Tên file MP4 mới nhất (out.mp4 hoặc out-r<n>.mp4 sau mỗi lần sửa), null nếu chưa có. */
export function currentOut(id) {
const st = readJson(path.join(editDir(id), 'state.json'), {});
@@ -20,35 +23,68 @@ export function currentOut(id) {
return null;
}
-export function readEditJob(id) {
- if (!ID_RE.test(String(id))) return null;
- return readJson(jobFile(id));
-}
function writeJob(id, patch) {
const cur = readJson(jobFile(id), {});
const next = { ...cur, ...patch, id, updatedAt: new Date().toISOString() };
fs.mkdirSync(editDir(id), { recursive: true });
- const tmp = jobFile(id) + '.tmp';
+ const tmp = jobFile(id) + `.${process.pid}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(next, null, 1));
fs.renameSync(tmp, jobFile(id));
return next;
}
+/**
+ * Job "queued"/"running" mà tiến trình giữ nó đã chết (CLI/MCP bị tắt, máy khởi động lại) → tự chuyển sang
+ * error (dựng lần đầu) hoặc done + reviseError (sửa, bản cũ vẫn còn), kèm lý do. Gọi ở mọi lần đọc.
+ */
+function reapIfDead(job) {
+ if (!job || !['queued', 'running'].includes(job.status) || pidAlive(job.pid)) return job;
+ const why = `bị ngắt giữa chừng (tiến trình ${job.pid || '?'} đã tắt lúc "${job.step || 'chờ lượt'}")`;
+ if (job.action === 'revise' && currentOut(job.id)) return writeJob(job.id, { status: 'done', reviseError: why + ' — bấm Render lại' });
+ return writeJob(job.id, { status: 'error', error: why + ' — bấm Dựng lại' });
+}
+
+export function readEditJob(id) {
+ if (!ID_RE.test(String(id))) return null;
+ return reapIfDead(readJson(jobFile(id)));
+}
+
/** Kiểu edit có sẵn (cho UI/MCP). */
export function editStyles() {
return listStyles().map((id) => { const s = loadStyle(id); return { id, order: s.order ?? 99, name: s.name, summary: s.guide.split('\n').find((l) => l.trim() && !l.startsWith('#')) || '' }; })
.sort((a, b) => a.order - b.order);
}
-/** Môi trường Python đã cài chưa (UI hiện hướng dẫn cài nếu chưa). */
+/** Đã cài đủ chưa (python, gói, model whisper, model mặt/người, font). UI hiện hướng dẫn cài nếu chưa. */
export function editReady() {
- return { ready: venvReady(), setup: 'node edit/setup.mjs', note: venvReady() ? '' : 'Chưa cài môi trường Edit video (Python 3.10–3.12, ~6 GB gồm whisper large-v3). Chạy trong thư mục LumReels: node edit/setup.mjs' };
+ const st = setupStatus();
+ return {
+ ready: st.ready, missing: st.missing, setup: 'node edit/setup.mjs',
+ note: st.ready ? '' : `Chưa cài đủ phần Edit video (thiếu: ${st.missing.join(', ')}). Cần Python 3.10–3.12, ~6 GB gồm whisper large-v3. Chạy trong thư mục LumReels: node edit/setup.mjs`,
+ };
+}
+
+/** ffprobe ngay khi tạo: video phải có hình + độ dài > 0; nhạc phải có tiếng. Lỗi → throw (chưa chạy whisper/LLM). */
+export async function checkMedia(video, music) {
+ let info;
+ try { info = await probeSource(video); } catch (e) { throw new Error(`không đọc được video (${path.basename(video)}): ${e.message}`); }
+ if (!Number.isFinite(info.duration) || info.duration < 1) throw new Error('video quá ngắn hoặc hỏng (dưới 1 giây)');
+ if (!info.hasAudio) throw new Error('video không có tiếng: cần tiếng nói để cắt và làm phụ đề');
+ if (info.duration > 30 * 60) throw new Error(`video dài ${Math.round(info.duration / 60)} phút; tối đa 30 phút`);
+ if (music) {
+ const { run } = await import('../engine/lib.mjs');
+ const r = await run('ffprobe', ['-v', 'error', '-select_streams', 'a:0', '-show_entries', 'stream=codec_type:format=duration', '-of', 'json', music]);
+ let j = null; try { j = JSON.parse(r.out); } catch { /* bỏ qua */ }
+ if (!j?.streams?.length) throw new Error(`file nhạc ${path.basename(music)} không có tiếng hoặc hỏng`);
+ }
+ return info;
}
/**
* Tạo hồ sơ edit (chưa chạy). input: {id?, video, style, music?, musicName?, content?, names?, draft?, llm?, sourceName?}
+ * Kiểm kiểu edit, file và ffprobe trước khi ghi job.json.
*/
-export function createEdit(input) {
+export async function createEdit(input) {
const id = input.id || newEditId();
if (!ID_RE.test(id)) throw new Error('id không hợp lệ');
const video = path.resolve(String(input.video || ''));
@@ -56,36 +92,93 @@ export function createEdit(input) {
const style = String(input.style || 'sach-gon');
if (!listStyles().includes(style)) throw new Error(`không có kiểu edit "${style}" (có: ${listStyles().join(', ')})`);
const music = input.music ? path.resolve(String(input.music)) : null;
- if (music && !fs.existsSync(music)) throw new Error(`không thấy file nhạc ${input.music}`);
+ if (music && (!fs.existsSync(music) || !fs.statSync(music).isFile())) throw new Error(`không thấy file nhạc ${input.music}`);
+ const info = await checkMedia(video, music);
const content = String(input.content || '').slice(0, 2000);
return writeJob(id, {
status: 'queued', action: 'edit', step: null, stepIndex: -1, stepTotal: STEPS.length, pct: 0, note: '',
- source: video, sourceName: input.sourceName || path.basename(video), style, music, musicName: input.musicName || (music ? path.basename(music) : null),
+ source: video, sourceName: input.sourceName || path.basename(video), sourceSeconds: +info.duration.toFixed(2),
+ style, music, musicName: input.musicName || (music ? path.basename(music) : null),
content, names: parseNames(input.names), draft: !!input.draft, llm: input.llm === 'off' ? 'off' : 'on',
- createdAt: new Date().toISOString(), error: null, out: null,
+ createdAt: new Date().toISOString(), error: null, out: null, pid: process.pid,
});
}
// ---- khoá toàn máy ------------------------------------------------------------------------------------------------
-async function withLock(id, fn) {
+function tryCreate(file, data) {
+ try { fs.writeFileSync(file, data, { flag: 'wx' }); return true; } catch (e) { if (e.code === 'EEXIST') return false; throw e; }
+}
+/** Gỡ khoá của tiến trình đã chết, dưới khoá phụ "wx" (chỉ 1 tiến trình được gỡ, và chỉ gỡ đúng khoá đã thấy là chết). */
+function breakStaleLock(seen) {
+ if (!tryCreate(BREAKER, JSON.stringify({ pid: process.pid, at: Date.now() }))) {
+ const b = readJson(BREAKER);
+ if (!b || (!pidAlive(b.pid) && Date.now() - (b.at || 0) > 5000)) { try { fs.unlinkSync(BREAKER); } catch { /* người khác vừa gỡ */ } }
+ return;
+ }
+ try {
+ const again = readJson(LOCK);
+ if (again && again.pid === seen.pid && again.at === seen.at && !pidAlive(again.pid)) fs.unlinkSync(LOCK);
+ } catch { /* đã bị gỡ */ } finally { try { fs.unlinkSync(BREAKER); } catch { /* bỏ qua */ } }
+}
+export async function withLock(id, fn) {
fs.mkdirSync(EDITS, { recursive: true });
- for (;;) {
- try {
- fs.writeFileSync(LOCK, JSON.stringify({ pid: process.pid, id, at: Date.now() }), { flag: 'wx' });
- break;
- } catch {
- const cur = readJson(LOCK);
- if (!cur || !pidAlive(cur.pid)) { try { fs.unlinkSync(LOCK); } catch { /* tiến trình khác vừa xoá */ } continue; }
- await new Promise((r) => setTimeout(r, 2000));
- }
+ const me = { pid: process.pid, id, at: Date.now() };
+ while (!tryCreate(LOCK, JSON.stringify(me))) {
+ const cur = readJson(LOCK);
+ if (cur && !pidAlive(cur.pid)) breakStaleLock(cur);
+ else await new Promise((r) => setTimeout(r, 2000));
+ }
+ try { return await fn(); } finally {
+ try { const cur = readJson(LOCK); if (cur?.pid === me.pid && cur?.at === me.at) fs.unlinkSync(LOCK); } catch { /* bỏ qua */ }
}
- try { return await fn(); } finally { try { const cur = readJson(LOCK); if (cur?.pid === process.pid && cur?.id === id) fs.unlinkSync(LOCK); } catch { /* bỏ qua */ } }
}
/** Edit đang chiếm khoá (nếu có). */
export function editLockHolder() { const cur = readJson(LOCK); return cur && pidAlive(cur.pid) ? cur : null; }
const onProgress = (id) => (p) => writeJob(id, { step: p.step, stepIndex: p.index, stepTotal: p.total, pct: p.pct, note: p.note || '' });
+// ---- dọn đĩa ---------------------------------------------------------------------------------------------------------
+/**
+ * Xong 1 lượt (dù được hay lỗi): xoá file trung gian lớn, chỉ giữ nguồn, edl, out*, phụ đề (index.html), log và
+ * các JSON nhỏ (phân tích, chép lời, mặt) để sửa bằng lời không phải phân tích lại. Proxy dựng lại từ nguồn khi cần.
+ */
+export function cleanupEdit(id) {
+ const dir = editDir(id);
+ let freed = 0;
+ const rm = (rel) => {
+ const f = path.join(dir, rel);
+ try {
+ const st = fs.statSync(f);
+ freed += st.isDirectory() ? dirBytes(f) : st.size;
+ fs.rmSync(f, { recursive: true, force: true });
+ } catch { /* không có */ }
+ };
+ for (const f of ['proxy.mov', 'base.mp4', 'base.words.json', 'base.face.json', 'captions.webm', 'audio', path.join('captions', 'lib'), 'qc.jpg', 'proxy.mov.part']) rm(f);
+ try { for (const f of fs.readdirSync(dir)) if (/\.part\.mp4$|\.tmp$/.test(f)) rm(f); } catch { /* bỏ qua */ }
+ return freed;
+}
+function dirBytes(d) {
+ let n = 0;
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
+ const f = path.join(d, e.name);
+ n += e.isDirectory() ? dirBytes(f) : fs.statSync(f).size;
+ }
+ return n;
+}
+
+/** Xoá hẳn 1 edit (thư mục edits/<id>). Đang chạy → throw. */
+export function deleteEdit(id) {
+ if (!ID_RE.test(String(id))) throw new Error('id không hợp lệ');
+ const job = readEditJob(id);
+ if (!job) throw new Error('không thấy edit ' + id);
+ if (['queued', 'running'].includes(job.status)) throw Object.assign(new Error('edit này đang chạy, chờ xong rồi xoá'), { code: 409 });
+ const dir = editDir(id);
+ if (path.dirname(dir) !== EDITS) throw new Error('đường dẫn lạ');
+ fs.rmSync(dir, { recursive: true, force: true });
+ return true;
+}
+
+// ---- chạy ------------------------------------------------------------------------------------------------------------
/** Chạy dựng lần đầu (chờ khoá). log: hàm in dòng (mặc định im lặng). */
export async function runEditJob(id, { log = () => {} } = {}) {
const job = readEditJob(id);
@@ -93,28 +186,39 @@ export async function runEditJob(id, { log = () => {} } = {}) {
writeJob(id, { status: 'queued', action: 'edit', error: null, pid: process.pid });
return withLock(id, async () => {
writeJob(id, { status: 'running', startedAt: new Date().toISOString(), pid: process.pid });
- const r = await editVideo(job.source, {
- id, style: job.style, music: job.music, content: job.content, names: job.names, draft: job.draft, llm: job.llm, log, progress: onProgress(id),
- });
- writeJob(id, r.ok ? { status: 'done', out: r.out, pct: 100, error: null } : { status: 'error', error: r.error });
+ let r;
+ try {
+ r = await editVideo(job.source, {
+ id, style: job.style, music: job.music, content: job.content, names: job.names, draft: job.draft, llm: job.llm, log, progress: onProgress(id),
+ });
+ } catch (e) { r = { ok: false, id, error: e.message }; }
+ const freed = cleanupEdit(id);
+ writeJob(id, r.ok ? { status: 'done', out: r.out, pct: 100, error: null, freedBytes: freed } : { status: 'error', error: r.error, freedBytes: freed });
return r;
});
}
-/** Sửa bằng lời rồi render lại (chờ khoá). Lỗi thì bản cũ vẫn giữ (status quay về done, ghi reviseError). */
-export async function reviseEditJob(id, instruction, { log = () => {} } = {}) {
+/**
+ * Sửa bằng lời rồi render lại. Kiểm đầu vào NGAY (throw đồng bộ: REST trả 4xx), rồi trả Promise chạy nền.
+ * Lỗi lúc chạy thì bản cũ vẫn giữ (status về done, ghi reviseError).
+ */
+export function reviseEditJob(id, instruction, { log = () => {} } = {}) {
const job = readEditJob(id);
- if (!job) throw new Error('không thấy edit ' + id);
- if (!fs.existsSync(path.join(editDir(id), 'state.json'))) throw new Error('edit này chưa dựng xong lần đầu');
+ if (!job) throw Object.assign(new Error('không thấy edit ' + id), { code: 404 });
+ if (['queued', 'running'].includes(job.status)) throw Object.assign(new Error('edit này đang chạy, chờ xong rồi sửa'), { code: 409 });
+ if (!fs.existsSync(path.join(editDir(id), 'state.json'))) throw Object.assign(new Error('edit này chưa dựng xong lần đầu'), { code: 409 });
const text = String(instruction || '').trim();
- if (!text) throw new Error('thiếu lời sửa');
+ if (!text) throw Object.assign(new Error('thiếu lời sửa'), { code: 400 });
+ if (text.length > 1000) throw Object.assign(new Error('lời sửa quá dài (tối đa 1000 ký tự)'), { code: 413 });
writeJob(id, { status: 'queued', action: 'revise', instruction: text, reviseError: null, pid: process.pid });
return withLock(id, async () => {
writeJob(id, { status: 'running', startedAt: new Date().toISOString(), stepIndex: 2, pid: process.pid });
- const r = await reviseEdit(id, text, { log, progress: onProgress(id) });
+ let r;
+ try { r = await reviseEdit(id, text, { log, progress: onProgress(id) }); } catch (e) { r = { ok: false, id, error: e.message }; }
+ const freed = cleanupEdit(id);
const hasOut = !!currentOut(id);
- writeJob(id, r.ok ? { status: 'done', out: r.out, pct: 100, reviseError: null }
- : { status: hasOut ? 'done' : 'error', reviseError: r.error, error: hasOut ? null : r.error });
+ writeJob(id, r.ok ? { status: 'done', out: r.out, pct: 100, reviseError: null, freedBytes: freed }
+ : { status: hasOut ? 'done' : 'error', reviseError: r.error, error: hasOut ? null : r.error, freedBytes: freed });
return r;
});
}
@@ -155,14 +259,8 @@ export function editView(id, { withLog = true, urlBase = `/edits/${id}` } = {})
export function listEdits(limit = 50) {
if (!fs.existsSync(EDITS)) return [];
return fs.readdirSync(EDITS).filter((d) => ID_RE.test(d) && fs.existsSync(jobFile(d)))
- .sort().reverse().slice(0, limit).map((id) => editView(id, { withLog: false }));
+ .sort().reverse().slice(0, limit).map((id) => editView(id, { withLog: false })).filter(Boolean);
}
-/** Server khởi động: edit "running"/"queued" mà tiến trình đã chết → báo lỗi (để người dùng bấm lại). */
-export function markStaleEdits() {
- for (const v of listEdits(200)) {
- if (['running', 'queued'].includes(v.status) && !(v.pid && pidAlive(v.pid))) {
- writeJob(v.id, { status: currentOut(v.id) && v.action === 'revise' ? 'done' : 'error', error: v.action === 'revise' ? null : 'bị ngắt giữa chừng (server/tiến trình đã tắt) — bấm Dựng lại', reviseError: v.action === 'revise' ? 'bị ngắt giữa chừng' : v.reviseError });
- }
- }
-}
+/** Server khởi động: quét mọi edit để job của tiến trình đã chết được chuyển trạng thái (readEditJob tự làm). */
+export function markStaleEdits() { listEdits(500); }
diff --git a/edit/pipeline.mjs b/edit/pipeline.mjs
index 389213d..66eeb40 100644
--- a/edit/pipeline.mjs
+++ b/edit/pipeline.mjs
@@ -15,7 +15,7 @@ import { run } from '../engine/lib.mjs';
import { SFX_NAMES } from '../engine/audio/sfx.mjs';
import { measureLoudness } from '../engine/audio/mix.mjs';
import { ROOT, runLumedit } from './env.mjs';
-import { ingest } from './ingest.mjs';
+import { ingest, makeProxy } from './ingest.mjs';
import {
loadStyle, wordList, propose, compileEdl, parseNames, proposeRevision, applyOverrides, applyExtraCuts, outputCutToSource,
} from './planner.mjs';
@@ -235,6 +235,14 @@ export async function reviseEdit(id, instruction, opts = {}) {
backup = path.join(vdir, `edl-${n}.json`);
fs.copyFileSync(path.join(dir, 'edl.json'), backup);
const next = { ...state, proposal: rev.proposal, overrides: rev.overrides, extraCuts: [...(state.extraCuts || []), ...newCuts] };
+ if (!fs.existsSync(ing.proxy.file)) {
+ // proxy bị dọn sau lượt trước (jobs.cleanupEdit): dựng lại từ nguồn, cùng thông số → cùng file (x264 tất định),
+ // nên cache chữ/mặt (proxy.words.json, proxy.face.json) dùng lại, không chép lời lại
+ if (!fs.existsSync(ing.source.file)) throw new Error('không còn file nguồn ' + ing.source.file);
+ const t = Date.now();
+ await makeProxy(ing.source.file, ing.info, ing.proxy.file, { log });
+ log(` dựng lại proxy từ nguồn: ${((Date.now() - t) / 1000).toFixed(1)} s`);
+ }
const edl = buildEdl({ id, ing, analysis, words, style, state: next, checks, log });
const outName = `out-r${n}.mp4`;
next.revisions = [...(state.revisions || []), { n, instruction, notes: rev.notes, at: new Date().toISOString(), previous: state.out || 'out.mp4', out: outName }];
diff --git a/edit/setup.mjs b/edit/setup.mjs
index 719365e..8c1ec96 100644
--- a/edit/setup.mjs
+++ b/edit/setup.mjs
@@ -13,7 +13,7 @@ import path from 'node:path';
import os from 'node:os';
import crypto from 'node:crypto';
import { spawnSync } from 'node:child_process';
-import { EDIT, ROOT, PACK, VENV, venvPython, pyEnv, dirSize, fmtBytes, WHISPER_MODEL } from './env.mjs';
+import { EDIT, ROOT, PACK, VENV, venvPython, pyEnv, dirSize, fmtBytes, WHISPER_MODEL, READY_MARK } from './env.mjs';
const args = new Set(process.argv.slice(2));
const say = (s) => console.log(s);
@@ -127,5 +127,19 @@ say(` model mặt/người (${path.relative(ROOT, path.join(PACK, 'models'))}):
say(` font Be Vietnam Pro: ${fmtBytes(fontsB)}`);
if (modelDir) say(` whisper ${WHISPER_MODEL}: ${fmtBytes(whisperB)} (${modelDir.replace(os.homedir(), '~')})`);
say(` tổng: ${fmtBytes(venvB + modelsB + fontsB + whisperB)}`);
+// ---- kiểm lần cuối + dấu READY (venvReady() đọc dấu này) ---------------------------------------------------------
+{
+ const r = sh(PY, ['-X', 'utf8', '-c', 'import mediapipe, faster_whisper, cv2, PIL, numpy, fontTools, ctranslate2; print("ok")'], { env: pyEnv() });
+ if (r.status !== 0) fail('NEED_PYTHON', 'Gói Python chưa đủ: ' + (r.stderr || '').trim().split(/\r?\n/).pop());
+ const files = [
+ ...['blaze_face_short_range.tflite', 'selfie_segmenter.tflite', 'face_landmarker.task'].map((f) => path.join(PACK, 'models', f)),
+ ...[600, 700, 800].map((w) => path.join(PACK, 'fonts', 'BeVietnamPro', `BeVietnamPro-${w}.ttf`)),
+ ...(modelDir ? [path.join(modelDir, 'model.bin')] : []),
+ ];
+ const lost = files.filter((f) => !fs.existsSync(f));
+ if (lost.length) fail('NEED_NETWORK', 'Thiếu file sau khi cài: ' + lost.join(', '));
+ if (!modelDir) say('(--skip-model: chưa ghi dấu READY vì chưa có model whisper)');
+ else fs.writeFileSync(READY_MARK, JSON.stringify({ at: new Date().toISOString(), whisper: WHISPER_MODEL, gpu, files }, null, 1));
+}
say(`PYTHON ${PY}`);
say('READY');
diff --git a/edit/test/http-abuse.mjs b/edit/test/http-abuse.mjs
new file mode 100644
index 0000000..d0ade50
--- /dev/null
+++ b/edit/test/http-abuse.mjs
@@ -0,0 +1,118 @@
+#!/usr/bin/env node
+// Tái hiện các lỗi QA của REST Edit video trên 1 server đang chạy (mặc định cổng 4416):
+// A2: 300 MB multipart không có dấu phân cách → phải 400 nhanh, RAM server không phình
+// A3: upload với style sai / musicStyle sai / video hỏng → 4xx và KHÔNG để lại edits/<id>/
+// A4: thiếu Content-Length → 411; 2 upload cùng lúc → 1 cái 429; DELETE
+// revise: id lạ → 404, lời rỗng → 400 (lỗi đồng bộ, không phải 202)
+// node edit/test/http-abuse.mjs [port] [serverPid]
+import fs from 'node:fs';
+import path from 'node:path';
+import http from 'node:http';
+import { execSync } from 'node:child_process';
+import { ROOT } from '../env.mjs';
+
+const PORT = Number(process.argv[2]) || 4416;
+const PID = process.argv[3];
+const HOST = `127.0.0.1:${PORT}`;
+const EDITS = path.join(ROOT, 'edits');
+const dirsNow = () => new Set(fs.existsSync(EDITS) ? fs.readdirSync(EDITS) : []);
+const rssMB = () => {
+ if (!PID) return null;
+ try {
+ const out = execSync(`tasklist /FI "PID eq ${PID}" /FO CSV /NH`, { encoding: 'utf8' });
+ return Math.round(Number(out.split('","')[4].replace(/[^\d]/g, '')) / 1024);
+ } catch { return null; }
+};
+let fails = 0;
+const check = (ok, what) => { console.log(`${ok ? 'PASS' : 'FAIL'} ${what}`); if (!ok) fails++; };
+
+function request({ method = 'POST', p = '/api/edits', headers = {}, body, stream }) {
+ return new Promise((resolve) => {
+ const t = Date.now();
+ const req = http.request({ host: '127.0.0.1', port: PORT, method, path: p, headers: { Host: HOST, ...headers } }, (res) => {
+ let d = ''; res.on('data', (c) => { d += c; }); res.on('end', () => resolve({ code: res.statusCode, body: d, ms: Date.now() - t }));
+ });
+ req.on('error', (e) => resolve({ code: -1, body: String(e.message), ms: Date.now() - t }));
+ if (stream) stream(req); else req.end(body);
+ });
+}
+function multipart(parts, boundary = 'XyZbOuNdArY123') {
+ const chunks = [];
+ for (const p of parts) {
+ chunks.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${p.name}"${p.filename ? `; filename="${p.filename}"` : ''}\r\n\r\n`));
+ chunks.push(Buffer.isBuffer(p.data) ? p.data : Buffer.from(String(p.data)));
+ chunks.push(Buffer.from('\r\n'));
+ }
+ chunks.push(Buffer.from(`--${boundary}--\r\n`));
+ return { body: Buffer.concat(chunks), type: `multipart/form-data; boundary=${boundary}` };
+}
+
+// ---- A2 ----
+{
+ const before = rssMB();
+ const total = 300 * 1024 ** 2; const chunk = Buffer.alloc(1024 * 1024, 0x41);
+ let peak = before;
+ const timer = setInterval(() => { const r = rssMB(); if (r && r > peak) peak = r; }, 500);
+ const r = await request({
+ headers: { 'Content-Type': 'multipart/form-data; boundary=XyZ', 'Content-Length': String(total) },
+ stream: (req) => {
+ let sent = 0;
+ const pump = () => { while (sent < total) { sent += chunk.length; if (!req.write(chunk)) { req.once('drain', pump); return; } } req.end(); };
+ req.on('error', () => {});
+ pump();
+ },
+ });
+ clearInterval(timer);
+ check((r.code === 400 || r.code === -1) && r.ms < 10000, `A2 300 MB không dấu phân cách → ${r.code} sau ${r.ms} ms (${r.body.slice(0, 80)})`);
+ if (before) check(peak - before < 100, `A2 RAM server: ${before} → đỉnh ${peak} MB`);
+}
+
+// ---- A3 ----
+const tiny = fs.readFileSync(path.join(ROOT, 'edits', '_synth', 'synth.mp4')).subarray(0, 300000); // video cụt (hỏng)
+const good = path.join(ROOT, 'edits', '_synth', 'synth.mp4');
+for (const [what, parts] of [
+ ['style sai', [{ name: 'style', data: 'khong-co' }, { name: 'video', filename: 'a.mp4', data: fs.readFileSync(good) }]],
+ ['musicStyle sai', [{ name: 'style', data: 'sach-gon' }, { name: 'musicStyle', data: 'khong-co' }, { name: 'video', filename: 'a.mp4', data: fs.readFileSync(good) }]],
+ ['video hỏng', [{ name: 'style', data: 'sach-gon' }, { name: 'video', filename: 'a.mp4', data: tiny }]],
+ ['đuôi file lạ', [{ name: 'style', data: 'sach-gon' }, { name: 'video', filename: 'a.exe', data: tiny }]],
+]) {
+ const pre = dirsNow();
+ const m = multipart(parts);
+ const r = await request({ headers: { 'Content-Type': m.type, 'Content-Length': String(m.body.length) }, body: m.body });
+ await new Promise((res) => setTimeout(res, 800));
+ const added = [...dirsNow()].filter((d) => !pre.has(d));
+ check(r.code >= 400 && r.code < 500 && added.length === 0, `A3 ${what} → ${r.code} ${JSON.parse(r.body || '{}').error || ''}; thư mục mới còn lại: ${added.length}`);
+}
+
+// ---- A4 ----
+{
+ const m = multipart([{ name: 'style', data: 'sach-gon' }, { name: 'video', filename: 'a.mp4', data: tiny }]);
+ const r = await request({ headers: { 'Content-Type': m.type, 'Transfer-Encoding': 'chunked' }, body: m.body });
+ check(r.code === 411, `A4 không có Content-Length → ${r.code}`);
+ // 2 upload cùng lúc: cái đầu gửi chậm
+ const m1 = multipart([{ name: 'style', data: 'sach-gon' }, { name: 'video', filename: 'a.mp4', data: tiny }]);
+ const slow = request({ headers: { 'Content-Type': m1.type, 'Content-Length': String(m1.body.length) }, stream: (req) => { req.write(m1.body.subarray(0, 1000)); setTimeout(() => req.end(m1.body.subarray(1000)), 2500); } });
+ await new Promise((res) => setTimeout(res, 500));
+ const r2 = await request({ headers: { 'Content-Type': m1.type, 'Content-Length': String(m1.body.length) }, body: m1.body });
+ const r1 = await slow;
+ check(r2.code === 429, `A4 upload thứ 2 trong lúc đang nhận → ${r2.code}; cái đầu (video hỏng) → ${r1.code}`);
+}
+
+// ---- revise / delete / origin ----
+{
+ const r = await request({ p: '/api/edits/khong-co-id/revise', headers: { 'Content-Type': 'application/json' }, body: '{"instruction":"x"}' });
+ check(r.code === 404, `revise id lạ → ${r.code}`);
+ const any = fs.readdirSync(EDITS).find((d) => fs.existsSync(path.join(EDITS, d, 'state.json')) && fs.existsSync(path.join(EDITS, d, 'job.json')));
+ if (any) {
+ const r2 = await request({ p: `/api/edits/${any}/revise`, headers: { 'Content-Type': 'application/json' }, body: '{"instruction":" "}' });
+ check(r2.code === 400, `revise lời rỗng → ${r2.code}`);
+ }
+ const r3 = await request({ method: 'DELETE', p: '/api/edits/khong-co-id' });
+ check(r3.code === 404, `DELETE id lạ → ${r3.code}`);
+ const r4 = await request({ method: 'DELETE', p: '/api/edits/abc', headers: { Origin: 'https://evil.example' } });
+ check(r4.code === 403, `DELETE từ Origin lạ → ${r4.code}`);
+ const r5 = await request({ method: 'GET', p: '/api/edits', headers: { Host: 'evil.example:4416' } });
+ check(r5.code === 421, `Host lạ (DNS rebinding) → ${r5.code}`);
+}
+console.log(fails ? `${fails} FAIL` : 'tất cả PASS');
+process.exit(fails ? 1 : 0);
diff --git a/mcp/server.mjs b/mcp/server.mjs
index f81e148..18ab067 100644
--- a/mcp/server.mjs
+++ b/mcp/server.mjs
@@ -283,7 +283,7 @@ server.registerTool('edit_video', {
musicFile = f;
} else musicFile = music;
}
- const job = createEdit({ video, style, music: musicFile, content: notes, names, draft });
+ const job = await createEdit({ video, style, music: musicFile, content: notes, names, draft });
const p = spawn(process.execPath, [path.join(ROOT, 'cli.mjs'), 'edit-run', job.id], { cwd: ROOT, detached: true, stdio: 'ignore', windowsHide: true, env: process.env });
p.unref();
return { content: [json({ ...editSummary(job.id), note: 'Đang dựng ở tiến trình nền. Gọi get_edit sau 1–2 phút.' })] };
@@ -300,7 +300,10 @@ server.registerTool('revise_edit', {
if (!job) return fail('Không thấy edit ' + editId);
if (['queued', 'running'].includes(job.status)) return fail('Edit này đang chạy, chờ xong rồi sửa (get_edit).');
if (!fs.existsSync(path.join(ROOT, 'edits', editId, 'state.json'))) return fail('Edit này chưa dựng xong lần đầu.');
- const p = spawn(process.execPath, [path.join(ROOT, 'cli.mjs'), 'edit-revise', editId, instruction], { cwd: ROOT, detached: true, stdio: 'ignore', windowsHide: true, env: process.env });
+ // lời sửa qua file, không qua argv (lời bắt đầu bằng '--' sẽ bị hiểu thành cờ)
+ const reqFile = path.join(ROOT, 'edits', editId, 'revise-request.txt');
+ fs.writeFileSync(reqFile, instruction);
+ const p = spawn(process.execPath, [path.join(ROOT, 'cli.mjs'), 'edit-revise', editId, '--file', reqFile], { cwd: ROOT, detached: true, stdio: 'ignore', windowsHide: true, env: process.env });
p.unref();
await new Promise((r) => setTimeout(r, 1500));
return { content: [json({ ...editSummary(editId), note: 'Đang sửa + render lại ở tiến trình nền. Gọi get_edit sau 1–2 phút.' })] };
diff --git a/scripts/mcp-smoke.mjs b/scripts/mcp-smoke.mjs
index 7d33aa3..a30a05c 100644
--- a/scripts/mcp-smoke.mjs
+++ b/scripts/mcp-smoke.mjs
@@ -11,11 +11,18 @@ const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const QUICK = process.argv.includes('--quick');
const SRC_JOB = process.argv.slice(2).find((a) => !a.startsWith('--')) || '261127064317-009-64b1';
+// Không bao giờ treo vô hạn: quá 300 s thì in bước đang chờ rồi thoát mã 1. Khởi động MCP server lâu nhất là nạp zod +
+// MCP SDK từ node_modules (đo 2–26 s trên ổ F: khi máy bận), không phải do tool nào.
+let phase = 'khởi động MCP server';
+const T0 = Date.now();
+setTimeout(() => { console.error(`smoke quá 300 s, đang chờ: ${phase}`); process.exit(1); }, 300_000).unref();
const transport = new StdioClientTransport({ command: process.execPath, args: [path.join(ROOT, 'mcp', 'server.mjs')], cwd: ROOT, env: { ...process.env }, stderr: 'ignore' });
const client = new Client({ name: 'smoke', version: '1.0.0' });
await client.connect(transport);
+console.log(`kết nối MCP server: ${((Date.now() - T0) / 1000).toFixed(1)} s`);
const short = (r) => r.content.map((c) => (c.type === 'text' ? c.text.slice(0, 400) : `[${c.type} ${c.mimeType} ${Math.round(c.data.length * 0.75 / 1024)} KB]`)).join('\n');
const call = async (name, args, opts) => {
+ phase = name;
const t = Date.now();
const r = await client.callTool({ name, arguments: args }, undefined, opts);
console.log(`\n=== ${name} (${((Date.now() - t) / 1000).toFixed(1)}s)${r.isError ? ' LỖI' : ''}\n${short(r)}`);
diff --git a/server/public/edit-panel.css b/server/public/edit-panel.css
index 25dc8d9..f7d48ea 100644
--- a/server/public/edit-panel.css
+++ b/server/public/edit-panel.css
@@ -64,7 +64,7 @@
.ed-revise button { min-height: 44px; padding: 0 16px; border-radius: 10px; border: 0; background: var(--accent); color: var(--accent-ink); font-weight: 700; cursor: pointer; white-space: nowrap; }
.ed-revise button:disabled { background: var(--panel-2); color: var(--ink-3); cursor: not-allowed; }
.ed-presets { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 8px; }
-.ed-presets button { min-height: 36px; padding: 0 12px; border-radius: 999px; border: 1px solid var(--line); background: var(--panel-2); color: var(--ink-2); font-size: 13px; cursor: pointer; }
+.ed-presets button { min-height: 44px; padding: 0 12px; border-radius: 999px; border: 1px solid var(--line); background: var(--panel-2); color: var(--ink-2); font-size: 13px; cursor: pointer; }
.ed-presets button:hover { color: var(--ink); }
.ed-hist ol { margin: 0; padding-left: 20px; color: var(--ink-2); font-size: 14px; }
.ed-checks { font-size: 13px; color: var(--ink-3); margin-top: 8px; line-height: 1.5; }
@@ -81,3 +81,8 @@
.ed-view { grid-template-columns: 1fr; }
.ed-media { max-width: 320px; width: 100%; justify-self: center; }
}
+
+.ed-danger { margin-top: 14px; }
+.ed-danger button { color: var(--bad); border-color: color-mix(in srgb, var(--bad) 40%, var(--line)); min-height: 44px; }
+.ed-danger button:hover { border-color: var(--bad); }
+.sty:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
diff --git a/server/public/edit-panel.js b/server/public/edit-panel.js
index 0095d43..d635fc5 100644
--- a/server/public/edit-panel.js
+++ b/server/public/edit-panel.js
@@ -32,24 +32,46 @@
const o = state.opts;
if (!o.ready) { $('#edSetup').hidden = false; $('#edSetupText').innerHTML = `${esc(o.note)}`; $('#edSetupCmd').textContent = o.setup; }
state.style = o.styles[0]?.id || null;
- $('#edStyles').innerHTML = o.styles.map((s, i) => `<button type="button" class="sty" role="radio" aria-checked="${i === 0}" data-id="${esc(s.id)}"><span class="n">${esc(s.name)}</span><span class="d">${esc(s.summary)}</span></button>`).join('');
+ $('#edStyles').innerHTML = o.styles.map((s, i) => `<button type="button" class="sty" role="radio" aria-checked="${i === 0}" tabindex="${i === 0 ? 0 : -1}" data-id="${esc(s.id)}"><span class="n">${esc(s.name)}</span><span class="d">${esc(s.summary)}</span></button>`).join('');
$('#edMusic').innerHTML = '<option value="none">Không nhạc</option>'
+ o.music.map((m) => `<option value="${esc(m.id)}">Nhạc tổng hợp: ${esc(m.id)} — ${esc(m.desc)}</option>`).join('')
+ '<option value="file">Tải file nhạc của tôi…</option>';
refreshGo();
loadList();
}
- $('#edStyles').addEventListener('click', (e) => {
- const b = e.target.closest('.sty'); if (!b) return;
+ // radiogroup: bấm hoặc mũi tên chọn kiểu; chỉ nút đang chọn nằm trong thứ tự Tab (roving tabindex)
+ function pickStyle(b, focus) {
state.style = b.dataset.id;
- document.querySelectorAll('#edStyles .sty').forEach((x) => x.setAttribute('aria-checked', String(x === b)));
+ document.querySelectorAll('#edStyles .sty').forEach((x) => { x.setAttribute('aria-checked', String(x === b)); x.tabIndex = x === b ? 0 : -1; });
+ if (focus) b.focus();
+ }
+ $('#edStyles').addEventListener('click', (e) => { const b = e.target.closest('.sty'); if (b) pickStyle(b); });
+ $('#edStyles').addEventListener('keydown', (e) => {
+ const list = [...document.querySelectorAll('#edStyles .sty')];
+ const i = list.indexOf(document.activeElement);
+ if (i < 0) return;
+ const step = { ArrowDown: 1, ArrowRight: 1, ArrowUp: -1, ArrowLeft: -1 }[e.key];
+ if (step) { e.preventDefault(); pickStyle(list[(i + step + list.length) % list.length], true); }
+ else if (e.key === 'Home' || e.key === 'End') { e.preventDefault(); pickStyle(e.key === 'Home' ? list[0] : list[list.length - 1], true); }
});
+ // nhạc: chọn "Tải file…" mà huỷ hộp chọn file → trả select về lựa chọn trước
+ let musicPrev = 'none';
+ $('#edMusic').addEventListener('focus', () => { musicPrev = $('#edMusic').value; });
$('#edMusic').addEventListener('change', () => {
- const f = $('#edMusic').value === 'file';
- $('#edMusicFile').hidden = !f;
- if (f) $('#edMusicFile').click(); else { state.music = null; $('#edMusicName').textContent = ''; }
+ const v = $('#edMusic').value;
+ if (v === 'file') {
+ const inp = $('#edMusicFile');
+ const onFocusBack = () => setTimeout(() => { if (!inp.files.length && !state.music) $('#edMusic').value = musicPrev; }, 400);
+ window.addEventListener('focus', onFocusBack, { once: true });
+ inp.addEventListener('cancel', () => { if (!state.music) $('#edMusic').value = musicPrev; }, { once: true });
+ inp.click();
+ } else { state.music = null; $('#edMusicName').textContent = ''; musicPrev = v; }
+ });
+ $('#edMusicFile').addEventListener('change', (e) => {
+ state.music = e.target.files[0] || null;
+ if (!state.music) $('#edMusic').value = musicPrev;
+ $('#edMusicName').textContent = state.music ? `${state.music.name} · ${fmtMB(state.music.size)}` : '';
});
- $('#edMusicFile').addEventListener('change', (e) => { state.music = e.target.files[0] || null; $('#edMusicName').textContent = state.music ? `${state.music.name} · ${fmtMB(state.music.size)}` : ''; });
const drop = $('#edDrop');
const pickVideo = (f) => {
@@ -181,6 +203,7 @@
$('#edChecks').innerHTML = bits.join(' · ');
// sửa bằng lời
$('#edReviseBtn').disabled = busy || v.status !== 'done';
+ $('#edDelete').disabled = busy;
$('#edRevise').hidden = !(v.links?.out || v.status === 'done');
const revs = v.revisions || [];
$('#edHist').hidden = !revs.length;
@@ -199,6 +222,17 @@
render(j); poll();
} catch { $('#edViewErr').textContent = 'Không gửi được lời sửa.'; $('#edReviseBtn').disabled = false; }
}
+ $('#edDelete').addEventListener('click', async () => {
+ const id = state.current; if (!id) return;
+ if (!confirm('Xoá hẳn bản dựng này (video ra, EDL, file đã tải lên)? Không lấy lại được.')) return;
+ const r = await fetch(`/api/edits/${encodeURIComponent(id)}`, { method: 'DELETE' });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) { $('#edViewErr').textContent = j.error || `Lỗi ${r.status}`; return; }
+ clearTimeout(state.timer);
+ state.current = null; lastOut = null;
+ $('#edView').hidden = true; $('#edEmpty').hidden = false;
+ loadList();
+ });
$('#edReviseForm').addEventListener('submit', (e) => { e.preventDefault(); revise($('#edReviseText').value.trim()); });
$('#edPresets').addEventListener('click', (e) => { const b = e.target.closest('button'); if (b) $('#edReviseText').value = b.textContent; $('#edReviseText').focus(); });
diff --git a/server/public/index.html b/server/public/index.html
index f39e2e7..ac11841 100644
--- a/server/public/index.html
+++ b/server/public/index.html
@@ -130,18 +130,18 @@
<span class="big">Kéo thả video vào đây</span>
<span class="small">hoặc bấm để chọn · mp4, mov, mkv… tối đa 2 GB · nói trước máy, tiếng Việt</span>
</div>
- <input type="file" id="edVideo" accept="video/*,.mkv,.mov" hidden />
- <label class="field">Kiểu edit</label>
- <div class="styles" id="edStyles" role="radiogroup" aria-label="Kiểu edit"></div>
+ <label class="sr" for="edVideo">File video</label><input type="file" id="edVideo" accept="video/*,.mkv,.mov" hidden />
+ <span class="field" id="edStyleLbl">Kiểu edit</span>
+ <div class="styles" id="edStyles" role="radiogroup" aria-labelledby="edStyleLbl"></div>
<label class="field" for="edMusic">Nhạc nền <span class="opt">(tự hạ khi bạn nói)</span></label>
<select id="edMusic"><option value="none">Không nhạc</option></select>
- <input type="file" id="edMusicFile" accept="audio/*" hidden />
+ <label class="sr" for="edMusicFile">File nhạc</label><input type="file" id="edMusicFile" accept="audio/*" hidden />
<div class="ed-file" id="edMusicName"></div>
<label class="field" for="edNames">Tên riêng, thuật ngữ <span class="opt">(để AI viết phụ đề đúng)</span></label>
<input class="ed-in" id="edNames" type="text" maxlength="400" placeholder="Ví dụ: Lumfin, Hà Nội, ETF" autocomplete="off" />
<label class="field" for="edNotes">Dặn thêm <span class="opt">(không bắt buộc)</span></label>
<textarea id="edNotes" rows="3" maxlength="2000" placeholder="Ví dụ: bỏ câu chào đầu, giữ đoạn cuối kêu gọi theo dõi"></textarea>
- <label class="ed-check"><input type="checkbox" id="edDraft" /> Bản nháp nhanh (phụ đề đơn giản, nhanh hơn ~1 phút)</label>
+ <label class="ed-check" for="edDraft"><input type="checkbox" id="edDraft" /> Bản nháp nhanh (phụ đề đơn giản, nhanh hơn ~1 phút)</label>
<p class="err" id="edErr" role="alert"></p>
<button id="edGo" class="go" disabled>
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 4v16l13-8z"/></svg>
@@ -177,6 +177,7 @@
</div>
<div class="ed-hist" id="edHist" hidden><h4>Các lần sửa</h4><ol id="edHistList"></ol></div>
<details class="log"><summary>Nhật ký</summary><pre id="edLog"></pre></details>
+ <div class="links ed-danger"><button type="button" id="edDelete">Xoá bản dựng này</button></div>
</div>
</div>
</div>