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.
Nhật ký lỗi cho người dùng: panel Nhật ký trên thẻ job/edit/Studio, câu lỗi dễ hiểu, nhật ký app
Lumtek5bb3b03da067
diff --git a/edit/jobs.mjs b/edit/jobs.mjsindex 1b71a9c..469c3d1 100644--- a/edit/jobs.mjs+++ b/edit/jobs.mjs@@ -11,6 +11,7 @@ import { listStyles, loadStyle, parseNames, STYLES_DIR } from './planner.mjs';import { setupStatus } from './env.mjs';import { resolveEditStyle } from '../packs/registry.mjs';import { probeSource } from './ingest.mjs';+import { redact } from '../server/logs.mjs';export { STEPS, EDITS, newEditId, editDir };export const ID_RE = /^[\w-]{1,80}$/;@@ -370,6 +371,8 @@ export function editView(id, { withLog = true, urlBase = `/edits/${id}` } = {})},files: { dir, out: outName ? path.join(dir, outName) : null, edl: has('edl.json') ? path.join(dir, 'edl.json') : null },};+ if (v.error) v.error = redact(v.error);+ if (v.reviseError) v.reviseError = redact(v.reviseError);if (withLog) {try { v.log = fs.readFileSync(path.join(dir, 'log.txt'), 'utf8').trim().split(/\r?\n/).slice(-40); } catch { v.log = []; }}diff --git a/server/logs.mjs b/server/logs.mjsnew file mode 100644index 0000000..b0ea7c4--- /dev/null+++ b/server/logs.mjs@@ -0,0 +1,223 @@+// Nhật ký cho người dùng: xem vì sao 1 job hỏng mà không mở terminal.+// GET /api/logs/job/:id → job dựng từ mẫu (jobs/<id>/log.txt)+// GET /api/logs/edit/:id → job edit (edits/<id>/log.txt)+// GET /api/logs/server → log server gần nhất (ring buffer trong RAM + đuôi logs/server.log nếu file đó đã có)+// thêm ?download=1 → text/plain kèm Content-Disposition (nút "Tải file .txt")+// Chỉ đọc. id kiểm chặt (^[\w-]{1,80}$, không có "." nên không ".."), Origin lạ → 403 như các route ghi.+// Mọi chữ trả ra đã qua redact(): khoá API (sk-…), KEY=/TOKEN=, header Authorization/Bearer, x-api-key, JWT,+// token GitHub/Slack/AWS, ?key=/&token= trong URL; đường dẫn thư mục nhà rút về "~".+// explain(): map lỗi hay gặp sang mã (UI tra i18n "log.why.<mã>"); không khớp mã nào → UI hiện nguyên văn (đã lọc).+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++export const LOG_TAIL = 300; // số dòng cuối của log job trả ra+const RING_MAX = 1000; // số dòng log server giữ trong RAM+const MAX_LINE = 2000; // cắt dòng quá dài (traceback, JSON lỗi)+const ID_RE = /^[\w-]{1,80}$/;++// ---- lọc bí mật ------------------------------------------------------------------------------------------------+const HIDE = '[đã ẩn]';+const homeForms = (() => {+ const h = os.homedir();+ if (!h || h.length < 3) return [];+ const fwd = h.replace(/\\/g, '/');+ const set = new Set([h, fwd, h.replace(/\\/g, '\\\\'), fwd.replace(/^([A-Za-z]):/, (m, d) => `/${d.toLowerCase()}`)]);+ return [...set].sort((a, b) => b.length - a.length);+})();+const reEsc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+const HOME_RE = homeForms.length ? new RegExp(homeForms.map(reEsc).join('|'), 'gi') : null;+const RULES = [+ // KEY=..., TOKEN: ..., "api_key": "...", password=... (tên biến/thuộc tính chứa key/token/secret/password)+ [/((?:["']?)[A-Za-z0-9_.-]*(?:api[_-]?key|apikey|secret|token(?![sS])|passw(?:or)?d|auth[_-]?key|access[_-]?key|private[_-]?key)[A-Za-z0-9_.-]*["']?\s*[:=]\s*)(["']?)[^\s"',;&]{3,}\2/gi, `$1$2${HIDE}$2`],+ // header Authorization / Proxy-Authorization / x-api-key / Cookie+ [/((?:proxy-)?authorization["']?\s*[:=]\s*["']?)(?:(?:bearer|basic|token)\s+)?[^\s"',;]+/gi, `$1${HIDE}`],+ [/((?:x-api-key|x-goog-api-key|api-key|cookie|set-cookie)["']?\s*[:=]\s*["']?)[^\s"',;]+/gi, `$1${HIDE}`],+ [/\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, `$1 ${HIDE}`],+ // khoá dạng sk-… (Anthropic sk-ant-…, OpenAI sk-…/sk-proj-…), token GitHub/Slack/Google/AWS/HuggingFace, JWT+ [/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{8,}/g, `sk-${HIDE}`],+ [/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})/g, HIDE],+ [/\bxox[abposr]-[A-Za-z0-9-]{10,}/g, HIDE],+ [/\bAIza[0-9A-Za-z_-]{30,}/g, HIDE],+ [/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, HIDE],+ [/\bhf_[A-Za-z0-9]{20,}/g, HIDE],+ [/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, HIDE],+ // ?key=… &token=… trong URL+ [/([?&](?:key|api_key|apikey|token|access_token|auth|sig|signature)=)[^&\s"']+/gi, `$1${HIDE}`],+ // mật khẩu trong URL: scheme://user:pass@host+ [/(\b[a-z][a-z0-9+.-]*:\/\/[^\s:/@]+:)[^\s@/]+@/gi, `$1${HIDE}@`],+];+/** Lọc bí mật + rút đường dẫn nhà về "~". Nhận chuỗi bất kỳ, trả chuỗi. */+export function redact(text) {+ let s = String(text ?? '');+ for (const [re, to] of RULES) s = s.replace(re, to);+ if (HOME_RE) s = s.replace(HOME_RE, '~');+ return s;+}+const clip = (l) => (l.length > MAX_LINE ? l.slice(0, MAX_LINE) + ' …' : l);++// ---- câu lỗi dễ hiểu ---------------------------------------------------------------------------------------------+// Thứ tự = độ ưu tiên (cụ thể trước chung). UI: t('log.why.<code>') + t('log.fix.<code>').+const WHY = [+ ['claude_login', /please run \/login|not logged in|run `?claude login|invalid api key · please run|chưa đăng nhập claude|login required/i],+ ['api_key', /API 401|\b401\b\s*(?:\{|unauthori|authentication)|authentication_error|invalid[ _-]?(?:x-)?api[ _-]?key|incorrect api key|unauthori[sz]ed|permission_error/i],+ ['quota', /insufficient_quota|credit balance is too low|quota|billing|rate[_ ]limit|API 429|\b429\b\s*(?:\{|too many)|usage limit|hết hạn mức|limit reached|resets? at/i],+ ['overloaded', /overloaded_error|API 529|\b529\b\s*\{|overloaded|\b503\b service unavailable/i],+ ['disk', /ENOSPC|no space left|not enough space|disk (?:is )?full|ổ đĩa còn|hết dung lượng|There is not enough space/i],+ ['cuda', /CUDA|cudnn|cublas|libcudnn|nvcuda|CUBLAS_STATUS|out of memory.*GPU|GPU.*out of memory|ctranslate2.*cuda/i],+ ['ffmpeg', /(?:spawn|ENOENT).*ff(?:mpeg|probe)|ff(?:mpeg|probe)['"]? (?:is not recognized|not found)|không thấy ff(?:mpeg|probe)|ffmpeg: command not found|cần ffmpeg/i],+ ['python', /(?:spawn|ENOENT).*python|python(?:3)?['"]? (?:is not recognized|not found)|No module named|ModuleNotFoundError|môi trường Python|chưa cài đủ phần Edit/i],+ ['claude_missing', /không thấy lệnh claude|claude['"]? (?:is not recognized|not found)|(?:spawn|ENOENT).*claude/i],+ ['timeout', /timed? ?out|ETIMEDOUT|quá giờ|quá thời gian|hết giờ|timeout|render bị dừng|dừng sau \d+ phút|SIGTERM/i],+ ['interrupted', /server khởi động lại|bị ngắt giữa chừng|tiến trình .* đã tắt/i],+ ['network', /ENOTFOUND|ECONNREFUSED|ECONNRESET|EAI_AGAIN|getaddrinfo|network error|fetch failed|socket hang up/i],+ ['no_scene', /chưa có scene\/index\.html|Không thấy .*index\.html/i],+ ['scene_invalid', /Thiếu <div id="root"|#root thiếu|snapshot chỉ ra|HyperFrames render lỗi|SHADER_ERROR|lint/i],+ ['no_speech', /không nghe được lời nào|video không có tiếng/i],+ ['bad_video', /không đọc được video|video quá ngắn|hỏng \(dưới 1 giây\)|moov atom not found|Invalid data found/i],+ ['edl_invalid', /EDL không hợp lệ/i],+];+/** Tìm mã lỗi dễ hiểu trong câu lỗi (ưu tiên) rồi trong các dòng log cuối. Trả mã hoặc null. */+export function explain(error, lines = []) {+ const hay = [String(error || ''), ...lines.slice(-60).reverse()];+ for (const h of hay) {+ if (!h) continue;+ for (const [code, re] of WHY) if (re.test(h)) return code;+ }+ return null;+}+export const WHY_CODES = WHY.map(([c]) => c);++// ---- đọc đuôi file log -------------------------------------------------------------------------------------------+/** n dòng cuối của file (đọc tối đa 2 MB cuối, không nạp cả file lớn). */+export function tailFile(file, n = LOG_TAIL) {+ let fd;+ try {+ const st = fs.statSync(file);+ if (!st.isFile()) return { lines: [], total: 0, truncated: false };+ const len = Math.min(st.size, 2 * 1024 * 1024);+ const buf = Buffer.alloc(len);+ fd = fs.openSync(file, 'r');+ fs.readSync(fd, buf, 0, len, st.size - len);+ let all = buf.toString('utf8').split(/\r?\n/);+ if (st.size > len) all = all.slice(1); // dòng đầu có thể bị cắt giữa chừng+ all = all.filter((l) => l.length);+ return { lines: all.slice(-n), total: all.length, truncated: all.length > n || st.size > len };+ } catch { return { lines: [], total: 0, truncated: false }; } finally { if (fd !== undefined) try { fs.closeSync(fd); } catch { /* bỏ qua */ } }+}++// ---- log server: ring buffer -------------------------------------------------------------------------------------+const ring = [];+let ringFile = null;+let installed = false;+/**+ * Bắt console.log/info/warn/error vào ring buffer (giữ RING_MAX dòng). Có sẵn file logs/server.log (hoặc+ * LUMREELS_LOG_FILE) thì ghi thêm vào đó — không tự tạo file. Gọi 1 lần lúc server khởi động.+ */+export function installLogCapture(root) {+ if (installed) return;+ installed = true;+ const f = process.env.LUMREELS_LOG_FILE || path.join(root, 'logs', 'server.log');+ try { if (fs.statSync(f).isFile()) ringFile = f; } catch { /* không có file: chỉ RAM */ }+ for (const level of ['log', 'info', 'warn', 'error']) {+ const orig = console[level].bind(console);+ console[level] = (...args) => {+ orig(...args);+ try {+ const text = args.map((a) => (a instanceof Error ? (a.stack || a.message) : typeof a === 'string' ? a : (() => { try { return JSON.stringify(a); } catch { return String(a); } })())).join(' ');+ const stamp = new Date().toISOString().slice(0, 19).replace('T', ' ');+ for (const l of text.split(/\r?\n/)) {+ if (!l) continue;+ const line = `[${stamp}]${level === 'error' ? ' LỖI' : level === 'warn' ? ' CẢNH BÁO' : ''} ${clip(l)}`;+ ring.push(line);+ if (ringFile) try { fs.appendFileSync(ringFile, redact(line) + '\n'); } catch { ringFile = null; }+ }+ if (ring.length > RING_MAX) ring.splice(0, ring.length - RING_MAX);+ } catch { /* log không được thì thôi */ }+ };+ }+}+/** Log server gần nhất (đã lọc). Ring ít dòng (vừa khởi động lại) → nối đuôi file log nếu có. */+export function serverLog(n = LOG_TAIL) {+ let lines = ring.slice(-n);+ let source = 'memory';+ if (lines.length < n && ringFile) {+ const ft = tailFile(ringFile, n);+ const have = new Set(lines);+ const older = ft.lines.filter((l) => !have.has(l));+ if (older.length) { lines = [...older.slice(-(n - lines.length)), ...lines]; source = 'memory+file'; }+ }+ return { kind: 'server', source, lines: lines.map((l) => clip(redact(l))), total: ring.length, truncated: ring.length > n, at: new Date().toISOString() };+}++// ---- nhật ký 1 job ------------------------------------------------------------------------------------------------+const TPL_STEPS = ['generating', 'waiting_agent', 'previewing', 'rendering'];+/** Bước hỏng của job dựng từ mẫu: trạng thái cuối cùng trước "error" trong log ("trạng thái → X"). */+function tplFailedStep(lines) {+ let last = null;+ for (const l of lines) {+ const m = /trạng thái → (\w+)/.exec(l);+ if (!m) continue;+ if (m[1] === 'error') return last;+ if (TPL_STEPS.includes(m[1])) last = m[1];+ }+ return null;+}+/**+ * Nhật ký job: {kind, id, status, step, error, why, lines[], total, truncated}. Mọi chữ đã lọc.+ * kind 'job' (dựng từ mẫu, step = mã trạng thái: generating | previewing | rendering …) hoặc 'edit' (step = tên bước edit).+ */+export function jobLog(kind, id, { jobsDir, editsDir, readJob, readEdit }) {+ if (!ID_RE.test(String(id))) return null;+ const base = kind === 'edit' ? editsDir : jobsDir;+ const dir = path.resolve(base, id);+ if (path.dirname(dir) !== path.resolve(base)) return null;+ const job = kind === 'edit' ? readEdit(id) : readJob(id);+ if (!job) return null;+ const t = tailFile(path.join(dir, 'log.txt'));+ const failed = job.status === 'error' || (kind === 'edit' && !!job.reviseError);+ const error = kind === 'edit' ? (job.status === 'error' ? job.error : job.reviseError) || null : job.status === 'error' ? job.error || null : null;+ let step = null;+ if (failed) step = kind === 'edit' ? job.step || null : tplFailedStep(t.lines);+ return {+ kind, id, status: job.status, failed, step, error: error ? clip(redact(error)) : null,+ why: failed ? explain(error, t.lines) : null,+ lines: t.lines.map((l) => clip(redact(l))), total: t.total, truncated: t.truncated,+ title: kind === 'edit' ? redact(job.sourceName || '') : redact(job.templateTitle || job.templateId || ''),+ at: new Date().toISOString(),+ };+}++/** Văn bản .txt để tải về / chép (đầu: trạng thái, bước, lỗi; rồi log thô). */+export function logText(v) {+ const head = v.kind === 'server'+ ? [`LumReels — nhật ký server (${v.at})`, `nguồn: ${v.source}, ${v.lines.length} dòng`]+ : [`LumReels — nhật ký ${v.kind === 'edit' ? 'edit' : 'job'} ${v.id}${v.title ? ` (${v.title})` : ''}`, `trạng thái: ${v.status}${v.step ? ` · bước hỏng: ${v.step}` : ''}`,+ ...(v.error ? [`lỗi: ${v.error}`] : []), ...(v.why ? [`mã lỗi: ${v.why}`] : []), `xuất lúc: ${v.at}`];+ return `${head.join('\n')}\n${'-'.repeat(60)}\n${v.lines.join('\n')}\n`;+}++/** Route /api/logs/…; trả true nếu đã xử lý. ctx: {send, originOk(req), jobsDir, editsDir, readJob, readEdit}. */+export function handleLogRoute(req, res, p, url, ctx) {+ if (!p.startsWith('/api/logs')) return false;+ if (req.method !== 'GET' && req.method !== 'HEAD') { ctx.send(res, 405, { error: 'chỉ đọc' }); return true; }+ // Origin lạ (trang web khác gọi fetch) → 403; không có Origin (cùng trang / curl cục bộ) thì cho.+ if (!ctx.originOk(req)) { ctx.send(res, 403, { error: 'origin không hợp lệ' }); return true; }+ let v = null;+ if (p === '/api/logs/server') v = serverLog();+ else {+ const m = /^\/api\/logs\/(job|edit)\/([^/]+)$/.exec(p);+ if (!m) { ctx.send(res, 404, { error: 'không có API này' }); return true; }+ if (!ID_RE.test(m[2])) { ctx.send(res, 400, { error: 'id không hợp lệ' }); return true; }+ v = jobLog(m[1], m[2], ctx);+ if (!v) { ctx.send(res, 404, { error: 'không thấy job' }); return true; }+ }+ if (url.searchParams.get('download') === '1') {+ const name = v.kind === 'server' ? 'lumreels-server-log.txt' : `lumreels-${v.kind}-${v.id}-log.txt`;+ res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8', 'Content-Disposition': `attachment; filename="${name}"`, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });+ res.end(req.method === 'HEAD' ? undefined : logText(v));+ return true;+ }+ ctx.send(res, 200, v);+ return true;+}diff --git a/server/public/app.js b/server/public/app.jsindex f46ec89..7813ac6 100644--- a/server/public/app.js+++ b/server/public/app.js@@ -441,8 +441,9 @@${j.links?.brief ? `<a href="${j.links.brief}" target="_blank" rel="noopener">Brief</a>` : ''}${j.status === 'done' && j.links?.mp4 ? `<button type="button" class="to-studio" data-studio="${j.id}">${esc(t('job.studio'))}</button>` : ''}${['waiting_agent', 'error', 'done'].includes(j.status) ? `<button data-render="${j.id}">${esc(t(j.status === 'done' ? 'job.rerender' : 'job.render'))}</button>` : ''}+ <button type="button" class="log-btn${j.status === 'error' ? ' bad' : ''}" data-log-kind="job" data-log-id="${j.id}">${esc(t(j.status === 'error' ? 'log.btnErr' : 'log.btn'))}</button></div>- ${j.log?.length ? `<details class="log"><summary>${esc(t('job.log', { n: j.log.length }))}</summary><pre>${esc(j.log.join('\n'))}</pre></details>` : ''}+ ${running && j.log?.length ? `<details class="log"><summary>${esc(t('job.log', { n: j.log.length }))}</summary><pre>${esc(j.log.join('\n'))}</pre></details>` : ''}</div></article>`;}diff --git a/server/public/i18n.js b/server/public/i18n.jsindex 987d445..69c9a1e 100644--- a/server/public/i18n.js+++ b/server/public/i18n.js@@ -763,6 +763,33 @@'gf.row': 'Dòng {n}', 'gf.ok': 'Đánh dấu ✓','gfx.counter': 'Số đếm', 'gfx.bar_chart': 'Biểu đồ cột', 'gfx.compare': 'So sánh', 'gfx.spec_table': 'Bảng','gfx.checklist': 'Checklist', 'gfx.price_tag': 'Tem giá', 'gfx.sticker': 'Sticker', 'gfx.line_chart': 'Biểu đồ đường', 'gfx.title_card': 'Thẻ tiêu đề',++ // ---- nhật ký (log-panel.js) ----+ 'log.btn': 'Nhật ký', 'log.btnErr': 'Xem lỗi', 'log.appBtn': 'Nhật ký app',+ 'log.title': 'Nhật ký', 'log.titleServer': 'Nhật ký app', 'log.subServer': 'Log server gần nhất (chỉ trong máy này)',+ 'log.close': 'Đóng nhật ký', 'log.copy': 'Chép nhật ký', 'log.copied': 'Đã chép', 'log.copyManual': 'Đã chọn chữ, bấm Ctrl+C',+ 'log.download': 'Tải file .txt', 'log.reload': 'Tải lại', 'log.loading': 'Đang đọc nhật ký…', 'log.loadErr': 'Không đọc được nhật ký: {e}',+ 'log.step': 'Hỏng ở bước: {s}', 'log.rawError': 'Câu lỗi gốc', 'log.whyUnknown': 'Lỗi chưa có trong danh sách quen. Câu lỗi gốc ở dưới, chép nhật ký gửi người hỗ trợ.',+ 'log.okDone': 'Job này chạy xong, không có lỗi.', 'log.okRunning': 'Job chưa xong hoặc chưa lỗi. Bấm Tải lại để xem dòng mới.',+ 'log.serverNote': (v) => `${v.n} dòng log gần nhất của server. Khoá API, token và đường dẫn thư mục nhà đã được ẩn.`,+ 'log.rawHead': (v) => (v.total > v.n ? `Log thô: ${v.n} dòng cuối (trong ${v.total} dòng)` : `Log thô: ${v.n} dòng`), 'log.empty': 'Chưa có dòng log nào.',+ 'log.why.claude_login': 'Claude Code chưa đăng nhập.', 'log.fix.claude_login': 'Mở terminal, chạy lệnh claude rồi gõ /login, đăng nhập xong bấm Render lại.',+ 'log.why.api_key': 'Khoá Claude API sai hoặc đã bị thu hồi (lỗi 401).', 'log.fix.api_key': 'Sửa ANTHROPIC_API_KEY trong file .env (lấy khoá mới ở console.anthropic.com), khởi động lại app rồi dựng lại. Hoặc chọn "Claude Code" ở ô Ai dựng cảnh.',+ 'log.why.quota': 'Hết hạn mức hoặc bị giới hạn tốc độ của AI.', 'log.fix.quota': 'Nạp thêm tiền / chờ hạn mức mở lại, hoặc đổi sang model rẻ hơn (Haiku) rồi dựng lại.',+ 'log.why.overloaded': 'Máy chủ AI đang quá tải.', 'log.fix.overloaded': 'Chờ vài phút rồi bấm Render lại.',+ 'log.why.disk': 'Ổ đĩa hết chỗ trống.', 'log.fix.disk': 'Xoá bớt video cũ (job, bản edit) hoặc dọn ổ đĩa, cần trống vài GB, rồi dựng lại.',+ 'log.why.cuda': 'Chép lời bằng GPU lỗi (thiếu CUDA/cuDNN hoặc GPU hết bộ nhớ).', 'log.fix.cuda': 'Cập nhật driver NVIDIA, đóng app đang dùng GPU, hoặc chạy lại node edit/setup.mjs. Không có GPU thì app tự chép lời bằng CPU (chậm hơn).',+ 'log.why.ffmpeg': 'Máy chưa có ffmpeg (hoặc không tìm thấy).', 'log.fix.ffmpeg': 'Cài ffmpeg (winget install ffmpeg trên Windows, brew install ffmpeg trên Mac) rồi khởi động lại app.',+ 'log.why.python': 'Thiếu Python hoặc gói Python cho phần Edit video.', 'log.fix.python': 'Cài Python 3.10–3.12, rồi bấm "Cài ngay" ở tab Edit video (hoặc chạy node edit/setup.mjs).',+ 'log.why.claude_missing': 'Không tìm thấy lệnh claude (Claude Code).', 'log.fix.claude_missing': 'Cài Claude Code (npm i -g @anthropic-ai/claude-code), hoặc chọn "Claude API" nếu đã có khoá API.',+ 'log.why.timeout': 'Quá thời gian cho phép (AI viết cảnh hoặc render chạy quá lâu).', 'log.fix.timeout': 'Rút ngắn thời lượng, chọn mẫu 2D nhẹ hơn, hoặc dựng lại lúc máy rảnh.',+ 'log.why.interrupted': 'App bị tắt khi job đang chạy.', 'log.fix.interrupted': 'Bấm Render lại / Dựng lại để chạy tiếp.',+ 'log.why.network': 'Mất mạng hoặc không kết nối được máy chủ.', 'log.fix.network': 'Kiểm tra mạng rồi thử lại.',+ 'log.why.no_scene': 'AI chưa viết xong cảnh (thiếu scene/index.html).', 'log.fix.no_scene': 'Bấm Render lại; nếu vẫn lỗi, xem log thô để biết AI dừng ở đâu.',+ 'log.why.scene_invalid': 'Cảnh AI viết có lỗi nên không render được.', 'log.fix.scene_invalid': 'Bấm Render lại để AI sửa, hoặc dựng lại với model mạnh hơn.',+ 'log.why.no_speech': 'Video không có tiếng nói nghe được.', 'log.fix.no_speech': 'Chọn clip có người nói rõ (tiếng Việt), không phải nhạc nền.',+ 'log.why.bad_video': 'File video hỏng hoặc định dạng không đọc được.', 'log.fix.bad_video': 'Xuất lại video sang MP4 (H.264) rồi tải lên lại.',+ 'log.why.edl_invalid': 'Bản dựng AI lập bị lệch (đoạn cắt, zoom, tiếng không khớp).', 'log.fix.edl_invalid': 'Bấm Dựng lại; lần sau AI sẽ lập lại từ đầu.',};const en = {@@ -1524,6 +1551,33 @@'gf.row': 'Row {n}', 'gf.ok': 'Tick ✓','gfx.counter': 'Counter', 'gfx.bar_chart': 'Bar chart', 'gfx.compare': 'Compare', 'gfx.spec_table': 'Table','gfx.checklist': 'Checklist', 'gfx.price_tag': 'Price tag', 'gfx.sticker': 'Sticker', 'gfx.line_chart': 'Line chart', 'gfx.title_card': 'Title card',++ // ---- log panel ----+ 'log.btn': 'Log', 'log.btnErr': 'See error', 'log.appBtn': 'App log',+ 'log.title': 'Log', 'log.titleServer': 'App log', 'log.subServer': 'Latest server log (this computer only)',+ 'log.close': 'Close log', 'log.copy': 'Copy log', 'log.copied': 'Copied', 'log.copyManual': 'Text selected, press Ctrl+C',+ 'log.download': 'Download .txt', 'log.reload': 'Reload', 'log.loading': 'Reading the log…', 'log.loadErr': 'Could not read the log: {e}',+ 'log.step': 'Failed at step: {s}', 'log.rawError': 'Original error', 'log.whyUnknown': 'This error is not on the known list. The original message is below; copy the log and send it to support.',+ 'log.okDone': 'This job finished without errors.', 'log.okRunning': 'The job has not finished or failed yet. Hit Reload for new lines.',+ 'log.serverNote': (v) => `The last ${v.n} server log line${S(v.n)}. API keys, tokens and home-folder paths are hidden.`,+ 'log.rawHead': (v) => (v.total > v.n ? `Raw log: last ${v.n} of ${v.total} lines` : `Raw log: ${v.n} line${S(v.n)}`), 'log.empty': 'No log lines yet.',+ 'log.why.claude_login': 'Claude Code is not signed in.', 'log.fix.claude_login': 'Open a terminal, run claude and type /login. Once signed in, hit Re-render.',+ 'log.why.api_key': 'The Claude API key is wrong or revoked (error 401).', 'log.fix.api_key': 'Fix ANTHROPIC_API_KEY in the .env file (get a new key at console.anthropic.com), restart the app and build again. Or pick "Claude Code" under Who writes the scenes.',+ 'log.why.quota': 'The AI usage limit or rate limit was hit.', 'log.fix.quota': 'Top up / wait for the limit to reset, or switch to a cheaper model (Haiku) and build again.',+ 'log.why.overloaded': 'The AI servers are overloaded.', 'log.fix.overloaded': 'Wait a few minutes, then hit Re-render.',+ 'log.why.disk': 'The disk is full.', 'log.fix.disk': 'Delete old videos (jobs, edits) or free up disk space (a few GB), then build again.',+ 'log.why.cuda': 'GPU transcription failed (CUDA/cuDNN missing or the GPU ran out of memory).', 'log.fix.cuda': 'Update the NVIDIA driver, close apps using the GPU, or run node edit/setup.mjs again. Without a GPU the app transcribes on the CPU (slower).',+ 'log.why.ffmpeg': 'ffmpeg is not installed (or cannot be found).', 'log.fix.ffmpeg': 'Install ffmpeg (winget install ffmpeg on Windows, brew install ffmpeg on Mac), then restart the app.',+ 'log.why.python': 'Python or the Python packages for Edit video are missing.', 'log.fix.python': 'Install Python 3.10–3.12, then hit "Install now" in the Edit video tab (or run node edit/setup.mjs).',+ 'log.why.claude_missing': 'The claude command (Claude Code) was not found.', 'log.fix.claude_missing': 'Install Claude Code (npm i -g @anthropic-ai/claude-code), or pick "Claude API" if you have an API key.',+ 'log.why.timeout': 'It ran out of time (scene writing or rendering took too long).', 'log.fix.timeout': 'Shorten the video, pick a lighter 2D template, or build again when the computer is idle.',+ 'log.why.interrupted': 'The app was closed while the job was running.', 'log.fix.interrupted': 'Hit Re-render / Build again to continue.',+ 'log.why.network': 'No network, or the server could not be reached.', 'log.fix.network': 'Check the connection and try again.',+ 'log.why.no_scene': 'The AI did not finish the scene (scene/index.html missing).', 'log.fix.no_scene': 'Hit Re-render; if it fails again, check the raw log to see where the AI stopped.',+ 'log.why.scene_invalid': 'The scene the AI wrote has errors and cannot render.', 'log.fix.scene_invalid': 'Hit Re-render so the AI fixes it, or build again with a stronger model.',+ 'log.why.no_speech': 'No speech could be heard in the video.', 'log.fix.no_speech': 'Pick a clip with clear speech (Vietnamese), not just music.',+ 'log.why.bad_video': 'The video file is broken or in a format that cannot be read.', 'log.fix.bad_video': 'Export the video as MP4 (H.264) and upload it again.',+ 'log.why.edl_invalid': 'The AI cut plan came out inconsistent (cuts, zooms or sounds do not match).', 'log.fix.edl_invalid': 'Hit Build again; the AI will plan from scratch.',};// Chuỗi tiếng Việt cố định do server trả cho giao diện (nhãn tuỳ chọn, bước dựng). Không gồm lỗi, tên mẫu, kiểu edit.diff --git a/server/public/index.html b/server/public/index.htmlindex 5ff8055..9b1beb4 100644--- a/server/public/index.html+++ b/server/public/index.html@@ -233,6 +233,7 @@<div class="cr-bact"><a class="btn pri" id="crOpen" hidden><span data-i18n="cr.open">Mở Studio</span></a><button type="button" class="btn ghost" id="crAnother" data-i18n="cr.another">Dựng clip khác</button>+ <button type="button" class="log-btn" id="crLog" data-log-kind="edit" data-log-id="">Nhật ký</button></div></div></div>@@ -251,6 +252,10 @@</div></section>+<footer class="app-foot">+ <button type="button" data-log-kind="server" data-i18n="log.appBtn">Nhật ký app</button>+</footer>+<dialog id="viewer" aria-label="Video minh hoạ của mẫu" data-i18n-aria="viewer.aria"><div class="dlg-head"><strong id="vTitle"></strong><button class="x" id="vClose" aria-label="Đóng" data-i18n-aria="viewer.close">×</button></div><video id="vVideo" controls playsinline preload="metadata"></video>@@ -258,6 +263,7 @@</dialog><script src="/i18n.js"></script>+<script src="/log-panel.js"></script><script src="/audio-panel.js"></script><script src="/voice-clone.js"></script><script src="/app.js"></script>diff --git a/server/public/log-panel.js b/server/public/log-panel.jsnew file mode 100644index 0000000..3f21b34--- /dev/null+++ b/server/public/log-panel.js@@ -0,0 +1,151 @@+// Bảng "Nhật ký": vì sao 1 job hỏng, không cần mở terminal. Dùng chung cho thẻ job (Dựng từ mẫu), thẻ edit, Studio+// và mục "Nhật ký app" ở chân trang. API chỉ đọc (server/logs.mjs): GET /api/logs/(job|edit)/:id, /api/logs/server,+// thêm ?download=1 để tải .txt. Server đã lọc bí mật; mọi chữ vào DOM bằng textContent.+// Gọi: window.LumLog.open({ kind: 'job' | 'edit' | 'server', id, title? }) · LumLog.button(kind, id, failed) → <button>.+(() => {+ const I = window.I18N;+ const t = (k, v) => I.t(k, v);+ const KINDS = ['job', 'edit', 'server'];+ const ID_RE = /^[\w-]{1,80}$/;+ let dlg = null; let cur = null; let data = null; let busy = false;++ function h(tag, cls, text, attrs = {}) {+ const e = document.createElement(tag);+ if (cls) e.className = cls;+ if (text != null) e.textContent = text;+ for (const [k, v] of Object.entries(attrs)) if (v != null) e.setAttribute(k, String(v));+ return e;+ }+ const url = (c, extra = '') => (c.kind === 'server' ? '/api/logs/server' : `/api/logs/${c.kind}/${encodeURIComponent(c.id)}`) + extra;++ function build() {+ dlg = h('dialog', 'logp', null, { 'aria-labelledby': 'logpTitle' });+ const head = h('div', 'logp-head');+ const ttl = h('div', 'logp-ttl');+ ttl.append(h('strong', null, '', { id: 'logpTitle' }), h('span', 'logp-sub'));+ const x = h('button', 'x', '×', { type: 'button' });+ x.addEventListener('click', () => dlg.close());+ head.append(ttl, x);+ const sum = h('div', 'logp-sum', null, { role: 'status', 'aria-live': 'polite' });+ const act = h('div', 'logp-act');+ const bCopy = h('button', 'mini logp-copy', '', { type: 'button' });+ const aDl = h('a', 'mini logp-dl', '', { download: '' });+ const bRe = h('button', 'mini logp-re', '', { type: 'button' });+ bCopy.addEventListener('click', copy);+ bRe.addEventListener('click', () => load());+ act.append(bCopy, aDl, bRe);+ const rawH = h('div', 'logp-rawh');+ const pre = h('pre', 'logp-raw', null, { tabindex: '0' });+ dlg.append(head, sum, act, rawH, pre);+ dlg.addEventListener('close', () => { cur = null; data = null; });+ document.body.append(dlg);+ }++ function paintStatic() {+ if (!dlg || !cur) return;+ dlg.querySelector('#logpTitle').textContent = t(cur.kind === 'server' ? 'log.titleServer' : 'log.title');+ dlg.querySelector('.logp-sub').textContent = cur.kind === 'server' ? t('log.subServer') : [cur.title || data?.title || '', cur.id].filter(Boolean).join(' · ');+ dlg.querySelector('.x').setAttribute('aria-label', t('log.close'));+ dlg.querySelector('.logp-copy').textContent = t('log.copy');+ const a = dlg.querySelector('.logp-dl'); a.textContent = t('log.download'); a.href = url(cur, '?download=1');+ dlg.querySelector('.logp-re').textContent = t('log.reload');+ }+ const stepName = (v) => {+ if (!v.step) return '';+ if (v.kind === 'job') return ['generating', 'waiting_agent', 'previewing', 'rendering'].includes(v.step) ? t('st.' + v.step) : v.step;+ return I.srv(v.step);+ };+ function paint() {+ paintStatic();+ if (!dlg || !cur) return;+ const sum = dlg.querySelector('.logp-sum'); const pre = dlg.querySelector('.logp-raw'); const rawH = dlg.querySelector('.logp-rawh');+ sum.replaceChildren(); sum.className = 'logp-sum';+ if (busy && !data) { sum.append(h('p', 'logp-muted', t('log.loading'))); pre.textContent = ''; rawH.textContent = ''; return; }+ if (data?.loadError) { sum.classList.add('bad'); sum.append(h('p', null, t('log.loadErr', { e: data.loadError }))); pre.textContent = ''; rawH.textContent = ''; return; }+ const v = data;+ if (!v) return;+ if (v.kind !== 'server') {+ const row = h('div', 'logp-row');+ const stCls = v.failed ? 'error' : v.status === 'done' ? 'done' : 'run';+ const stTxt = v.kind === 'job' ? (['scheduled', 'queued', 'generating', 'waiting_agent', 'previewing', 'rendering', 'done', 'error'].includes(v.status) ? t('st.' + v.status) : v.status)+ : (['queued', 'running', 'done', 'error'].includes(v.status) ? t('ed.st.' + v.status) : v.status);+ row.append(h('span', 'st ' + stCls, stTxt));+ if (v.failed && v.step) row.append(h('span', 'logp-step', t('log.step', { s: stepName(v) })));+ sum.append(row);+ if (v.failed) {+ sum.classList.add('bad');+ if (v.why) {+ sum.append(h('p', 'logp-why', t('log.why.' + v.why)));+ sum.append(h('p', 'logp-fix', t('log.fix.' + v.why)));+ } else sum.append(h('p', 'logp-why', t('log.whyUnknown')));+ if (v.error) {+ const d = h('details', 'logp-errd'); if (!v.why) d.open = true;+ d.append(h('summary', null, t('log.rawError')), h('code', 'logp-err', v.error));+ sum.append(d);+ }+ } else sum.append(h('p', 'logp-muted', t(v.status === 'done' ? 'log.okDone' : 'log.okRunning')));+ } else sum.append(h('p', 'logp-muted', t('log.serverNote', { n: v.lines.length })));+ rawH.textContent = v.lines.length ? t('log.rawHead', { n: v.lines.length, total: v.total }) : t('log.empty');+ const atEnd = pre.scrollTop + pre.clientHeight >= pre.scrollHeight - 8 || !pre.textContent;+ pre.textContent = v.lines.join('\n');+ if (atEnd) pre.scrollTop = pre.scrollHeight;+ }++ async function load() {+ if (!cur) return;+ const c = cur; busy = true; paint();+ try {+ const r = await fetch(url(c));+ const j = await r.json().catch(() => ({}));+ if (cur !== c) return;+ data = r.ok ? j : { loadError: I.srv(j.error || ('HTTP ' + r.status)) };+ } catch (e) { if (cur === c) data = { loadError: e.message }; }+ busy = false; paint();+ }+ function plainText() {+ const v = data; if (!v || v.loadError) return '';+ const head = [];+ if (v.kind === 'server') head.push(t('log.titleServer'));+ else {+ head.push(`${t('log.title')}: ${[cur?.title || v.title, v.id].filter(Boolean).join(' · ')}`);+ head.push(dlg.querySelector('.logp-row')?.textContent || v.status);+ if (v.failed) head.push(v.why ? `${t('log.why.' + v.why)} ${t('log.fix.' + v.why)}` : t('log.whyUnknown'));+ if (v.error) head.push(v.error);+ }+ return `${head.join('\n')}\n${'-'.repeat(40)}\n${v.lines.join('\n')}\n`;+ }+ async function copy() {+ const b = dlg.querySelector('.logp-copy'); const txt = plainText();+ let ok = false;+ try { await navigator.clipboard.writeText(txt); ok = true; } catch {+ // không có clipboard API (http, quyền): chọn chữ để người dùng Ctrl+C+ const pre = dlg.querySelector('.logp-raw'); const sel = getSelection(); const rg = document.createRange(); rg.selectNodeContents(pre); sel.removeAllRanges(); sel.addRange(rg);+ }+ b.textContent = t(ok ? 'log.copied' : 'log.copyManual');+ setTimeout(() => { if (b.isConnected) b.textContent = t('log.copy'); }, 1800);+ }++ function open(c) {+ if (!c || !KINDS.includes(c.kind) || (c.kind !== 'server' && !ID_RE.test(String(c.id || '')))) return;+ if (!dlg) build();+ cur = { kind: c.kind, id: c.id || null, title: c.title || '' }; data = null;+ paint();+ if (!dlg.open) dlg.showModal();+ load();+ }+ /** Nút "Nhật ký" (failed → nổi màu cảnh báo, chữ "Xem lỗi"). */+ function button(kind, id, failed, extraCls = '') {+ const b = h('button', `log-btn${failed ? ' bad' : ''}${extraCls ? ' ' + extraCls : ''}`, t(failed ? 'log.btnErr' : 'log.btn'), { type: 'button', 'data-log-kind': kind, 'data-log-id': id });+ return b;+ }+ // mọi nút có data-log-kind (vẽ bằng HTML chuỗi ở app.js hoặc bằng button()) → mở bảng+ document.addEventListener('click', (e) => {+ const b = e.target.closest?.('[data-log-kind]');+ if (!b) return;+ e.preventDefault(); e.stopPropagation();+ open({ kind: b.dataset.logKind, id: b.dataset.logId, title: b.dataset.logTitle || '' });+ }, true);+ window.addEventListener('lumreels:lang', () => { if (dlg?.open) paint(); });++ window.LumLog = { open, button };+})();diff --git a/server/public/studio/create.css b/server/public/studio/create.cssindex a817394..ce3a049 100644--- a/server/public/studio/create.css+++ b/server/public/studio/create.css@@ -210,3 +210,5 @@/* tab Dựng từ mẫu: nút Sửa tiếp trong Studio + nháy thẻ khi quay về từ Studio */.job .links .to-studio { background: var(--accent-soft); color: var(--accent); border-color: rgba(255,107,44,.5); font-weight: 600; }.job.flash { box-shadow: 0 0 0 3px var(--accent); transition: box-shadow .3s; }+.cr-log { margin-top: 6px; min-height: 36px; padding: 0 10px; font-size: 12.5px; }+.cr-log:not(.bad) { border-color: transparent; background: none; color: var(--ink-3); }diff --git a/server/public/studio/create.js b/server/public/studio/create.jsindex e22ac67..058dc2d 100644--- a/server/public/studio/create.js+++ b/server/public/studio/create.js@@ -285,6 +285,7 @@ function paintBuild(v) {$('#crBuildStep').textContent = busy && steps.length && v.status !== 'queued' ? t('ed.stepOf', { i: i + 1, n: steps.length, step: I.srv(steps[i]), p: v.pct || 0 }) : '';$('#crBuildErr').textContent = v.status === 'error' ? I.srv(v.error || t('ed.err')) : '';const o = $('#crOpen'); o.hidden = !(v.status === 'done' && v.links?.out); o.href = `#/edit/${encodeURIComponent(v.id)}`;+ const lg = $('#crLog'); lg.dataset.logId = v.id; lg.classList.toggle('bad', v.status === 'error'); lg.textContent = t(v.status === 'error' ? 'log.btnErr' : 'log.btn');const th = $('#crBuildThumb'); const pv = safeUrl(v.links?.previewFinal || v.links?.preview);th.style.backgroundImage = pv ? `url("${pv}")` : '';}@@ -321,7 +322,9 @@ function renderList() {const del = el('button', 'cr-del', null, { type: 'button', 'aria-label': t('cr.delete', { name: v.sourceName || v.id }), 'data-id': v.id, title: t('ed.delete') });del.append(el('span', null, '×', { 'aria-hidden': 'true' }));del.disabled = busy;- card.append(a, del);+ const bad = v.status === 'error' || !!v.reviseError;+ const lg = el('button', 'log-btn cr-log' + (bad ? ' bad' : ''), t(bad ? 'log.btnErr' : 'log.btn'), { type: 'button', 'data-log-kind': 'edit', 'data-log-id': v.id });+ card.append(a, del, lg);return card;}) : [el('p', 'cr-empty', t('ed.listEmpty'))]));}diff --git a/server/public/studio/studio.js b/server/public/studio/studio.jsindex 2ea1347..9c7ed87 100644--- a/server/public/studio/studio.js+++ b/server/public/studio/studio.js@@ -49,9 +49,10 @@ class Studio {this.bReset.addEventListener('click', () => { if (confirm(t('st.resetAsk'))) this.store.reset(); });this.bPub = el('button', 'btn pri st-pub', null, { type: 'button' });this.bPub.addEventListener('click', () => this.publish());+ this.bLog = el('button', 'btn ghost st-log', null, { type: 'button', 'data-log-kind': 'edit', 'data-log-id': '' });this.aDl = el('a', 'btn st-dl', null, { download: '' });this.aDl.append(icon('dl'), tx('span', null, 'ed.mp4'));- top.append(this.bBack, ttl, this.reelA, this.vers, mid, this.bReview, this.bReset, this.bPub, this.aDl);+ top.append(this.bBack, ttl, this.reelA, this.vers, mid, this.bReview, this.bReset, this.bLog, this.bPub, this.aDl);this.prog = el('div', 'st-prog', null, { role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': '100' }); this.prog.append(el('i')); this.prog.hidden = true;// giữaconst main = el('div', 'st-main');@@ -223,6 +224,11 @@ class Studio {this.bPub.hidden = !n && !this.publishing;this.bPub.disabled = busy || !n;this.bPub.replaceChildren(icon('upload'), el('span', null, this.publishing ? t('st.publishing') : t('st.publish', { n })));+ // nhật ký: lần xuất/sửa gần nhất lỗi (reviseError) hoặc job lỗi → nút nổi màu cảnh báo+ const bad = !!j && (j.status === 'error' || !!j.reviseError);+ this.bLog.dataset.logId = this.id || '';+ this.bLog.classList.toggle('bad', bad); this.bLog.classList.toggle('log-btn', bad);+ this.bLog.replaceChildren(el('span', null, t(bad ? 'log.btnErr' : 'log.btn')));const out = safeUrl(v?.media?.out || j?.links?.out);this.aDl.hidden = !out;if (out) { this.aDl.href = out; this.aDl.setAttribute('download', `${(name || 'video').replace(/\.[^.]+$/, '')}${v?.rev ? '-r' + v.rev : ''}.mp4`); }diff --git a/server/public/style.css b/server/public/style.cssindex 39dd4bc..fb9a04c 100644--- a/server/public/style.css+++ b/server/public/style.css@@ -190,3 +190,35 @@ dialog a { color: var(--accent); }.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); }++/* ---- Nhật ký (log-panel.js) ---- */+.log-btn { min-height: 40px; display: inline-flex; align-items: center; gap: 6px; padding: 0 12px; border-radius: 8px; border: 1px solid var(--line); background: var(--panel-2); color: var(--ink-2); font-size: 14px; cursor: pointer; }+.log-btn:hover { color: var(--ink); }+.log-btn.bad { color: var(--warn); border-color: rgba(242,201,76,.45); background: rgba(242,201,76,.1); font-weight: 600; }+.log-btn.bad::before { content: '!'; display: inline-grid; place-items: center; width: 18px; height: 18px; border-radius: 50%; background: var(--warn); color: #1A1400; font: 800 12px/1 var(--mono); }+dialog.logp { width: min(860px, 94vw); max-height: 88vh; max-height: 88dvh; display: flex; flex-direction: column; gap: 12px; padding: 18px; }+dialog.logp:not([open]) { display: none; }+.logp-head { display: flex; align-items: flex-start; gap: 12px; }+.logp-ttl { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }+.logp-ttl strong { font: 700 22px/1.2 var(--cond); text-transform: uppercase; letter-spacing: .03em; }+.logp-sub { color: var(--ink-3); font: 400 13px/1.4 var(--mono); overflow-wrap: anywhere; }+.logp .x { min-width: 44px; min-height: 44px; border-radius: 10px; border: 1px solid var(--line); background: var(--panel-2); color: var(--ink); font-size: 22px; cursor: pointer; }+.logp-sum { border: 1px solid var(--line); border-radius: 12px; padding: 12px 14px; background: var(--panel-2); display: flex; flex-direction: column; gap: 8px; }+.logp-sum.bad { border-color: rgba(242,201,76,.45); background: rgba(242,201,76,.07); }+.logp-sum p { margin: 0; line-height: 1.5; }+.logp-row { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }+.logp-step { color: var(--ink-2); font-size: 14px; }+.logp-why { font-weight: 600; font-size: 16px; color: var(--ink); }+.logp-fix { color: var(--ink-2); font-size: 14px; }+.logp-muted { color: var(--ink-2); font-size: 14px; }+.logp-errd summary { cursor: pointer; color: var(--ink-3); font-size: 13px; min-height: 28px; }+.logp-err { display: block; margin-top: 6px; white-space: pre-wrap; overflow-wrap: anywhere; font: 400 13px/1.5 var(--mono); color: var(--bad); max-height: 160px; overflow: auto; }+.logp-act { display: flex; flex-wrap: wrap; gap: 8px; }+.logp-act .mini { min-height: 40px; display: inline-flex; align-items: center; padding: 0 14px; border-radius: 8px; border: 1px solid var(--line); background: var(--panel-2); color: var(--ink); font-size: 14px; text-decoration: none; cursor: pointer; }+.logp-act .logp-copy { background: var(--ink); color: var(--bg); border-color: var(--ink); font-weight: 600; }+.logp-rawh { color: var(--ink-3); font-size: 13px; }+.logp-raw { margin: 0; flex: 1 1 auto; min-height: 160px; max-height: 50vh; overflow: auto; background: #0B0B0A; border: 1px solid var(--line); border-radius: 10px; padding: 12px; font: 400 12.5px/1.55 var(--mono); color: var(--ink-2); white-space: pre-wrap; overflow-wrap: anywhere; }+.app-foot { display: flex; justify-content: center; gap: 16px; padding: 8px 24px 32px; color: var(--ink-3); font-size: 13px; }+.app-foot button { min-height: 40px; padding: 0 12px; border-radius: 8px; border: 1px solid transparent; background: none; color: var(--ink-3); cursor: pointer; font-size: 13px; }+.app-foot button:hover { color: var(--ink); border-color: var(--line); }+body.studio-on .app-foot { display: none; }diff --git a/server/server.mjs b/server/server.mjsindex 4854cf0..d7b2f07 100644--- a/server/server.mjs+++ b/server/server.mjs@@ -22,6 +22,10 @@ import { listTemplates, resolveTemplate, parsePackRef, BUILTIN_TEMPLATE_RE } froimport { originOk } from '../edit/http.mjs';import { isCloneVoice, cloneRef } from '../engine/audio/voice-store.mjs';import { handleDraftRoute, initDrafts } from '../packs/drafts-http.mjs';+import { handleLogRoute, installLogCapture, redact } from './logs.mjs';+import { readEditJob, EDITS } from '../edit/jobs.mjs';++installLogCapture(ROOT); // log server vào ring buffer (GET /api/logs/server)const AUDIO_SAMPLES = path.join(ROOT, 'engine', 'audio', 'samples');/** File nghe thử (cache trong engine/audio/samples/, chỉ sinh khi chưa có). Trả đường dẫn tuyệt đối. */@@ -207,7 +211,8 @@ function jobView(job, withLog = false) {},paths: { dir, prompt: path.join(dir, 'PROMPT.md'), scene: path.join(dir, 'scene', 'index.html') },};- if (withLog) v.log = readLog(job.id, 120);+ if (v.error) v.error = redact(v.error);+ if (withLog) v.log = readLog(job.id, 120).map(redact);return v;}@@ -241,6 +246,8 @@ const server = http.createServer(async (req, res) => {return send(res, 403, { error: 'origin không hợp lệ' });}try {+ // ---- Nhật ký (server/logs.mjs): chỉ đọc, đã lọc bí mật ----+ if (handleLogRoute(req, res, p, url, { send, originOk: (r) => originOk(r, ALLOWED_HOSTS), jobsDir: JOBS, editsDir: EDITS, readJob, readEdit: readEditJob })) return;// ---- Gói mẫu .lumpack (packs/http.mjs) ----if (await handlePackRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS })) return;// ---- Edit video của bạn (edit/http.mjs) ----diff --git a/server/test/logs-check.mjs b/server/test/logs-check.mjsnew file mode 100644index 0000000..2ddab7f--- /dev/null+++ b/server/test/logs-check.mjs@@ -0,0 +1,144 @@+#!/usr/bin/env node+// Kiểm nhật ký (server/logs.mjs): lọc bí mật, câu lỗi dễ hiểu, đọc đuôi log, chặn path traversal + Origin lạ.+// node server/test/logs-check.mjs → chỉ phần không cần server+// node server/test/logs-check.mjs 4400 → thêm phần HTTP trên server đang chạy (chỉ GET, không ghi gì)+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import http from 'node:http';+import { redact, explain, tailFile, jobLog, logText } from '../logs.mjs';++let fail = 0; let pass = 0;+const ok = (cond, name, extra = '') => { if (cond) { pass++; console.log('PASS', name); } else { fail++; console.log('FAIL', name, extra); } };++// ---- 1. lọc bí mật ----+const home = os.homedir();+const SECRETS = [+ ['sk-ant-api03-AbCdEf1234567890_xyzXYZ-0987', 'khoá Anthropic sk-ant-'],+ ['sk-proj-ABCDEFGHIJKLMNOP1234567890', 'khoá OpenAI sk-proj-'],+ ['ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 'token GitHub'],+ ['xoxb-1234567890-abcdefghijkl', 'token Slack'],+ ['AIzaSyA1234567890abcdefghijklmnopqrstuv', 'khoá Google'],+ ['AKIAABCDEFGHIJKLMNOP', 'khoá AWS'],+ ['eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U', 'JWT'],+];+for (const [sec, name] of SECRETS) {+ const out = redact(`lỗi gọi API với ${sec} rồi`);+ ok(!out.includes(sec) && out.includes('[đã ẩn]'), `redact ${name}`, out);+}+const lines = {+ 'ANTHROPIC_API_KEY=abc123secretvalue': 'abc123secretvalue',+ 'export OPENAI_API_KEY="qwe-rty-123456"': 'qwe-rty-123456',+ 'MOTAPIS_API_KEY: zzzz9999': 'zzzz9999',+ 'GITHUB_TOKEN=gho_short123': 'gho_short123',+ 'Authorization: Bearer abcdef0123456789abcdef': 'abcdef0123456789abcdef',+ 'authorization: Basic dXNlcjpwYXNzd29yZA==': 'dXNlcjpwYXNzd29yZA==',+ '{"headers":{"x-api-key":"k-1234567890"}}': 'k-1234567890',+ '{"api_key": "hunter2hunter2"}': 'hunter2hunter2',+ 'password=Tr0ub4dor&3': 'Tr0ub4dor',+ 'GET https://api.example.com/v1?key=SECRETKEY123&x=1': 'SECRETKEY123',+ 'https://user:[email protected]/repo.git': 'pa55word',+ 'Cookie: session=abcdef123456': 'session=abcdef123456',+};+for (const [line, secret] of Object.entries(lines)) {+ const out = redact(line);+ ok(!out.includes(secret), `redact "${line.slice(0, 32)}…"`, out);+}+// không phá chữ thường: số token, đường dẫn trong job, tiếng Việt+ok(redact('in 12.3k / out 4.5k tokens, outputTokens: 4500').includes('4500'), 'redact giữ số token (không phải bí mật)');+ok(redact('trạng thái → error: HyperFrames render lỗi (mã 1)') === 'trạng thái → error: HyperFrames render lỗi (mã 1)', 'redact giữ nguyên câu tiếng Việt');+// đường dẫn nhà → ~+for (const p of [path.join(home, 'Videos', 'a.mp4'), home.replace(/\\/g, '/') + '/x/y.json', home.replace(/\\/g, '\\\\') + '\\\\z']) {+ const out = redact(`file ${p} lỗi`);+ ok(!out.toLowerCase().includes(home.toLowerCase()) && !out.toLowerCase().includes(home.replace(/\\/g, '/').toLowerCase()) && out.includes('~'), `redact đường dẫn nhà (${p.slice(-12)})`, out);+}++// ---- 2. câu lỗi dễ hiểu ----+const WHY = {+ 'API 401 AuthenticationError: 401 {"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}': 'api_key',+ 'Invalid API key · Please run /login': 'claude_login',+ 'API 429 {"type":"error","error":{"type":"rate_limit_error"}}': 'quota',+ 'Your credit balance is too low to access the Anthropic API': 'quota',+ 'spawn ffmpeg ENOENT': 'ffmpeg',+ "No module named 'faster_whisper'": 'python',+ 'ENOSPC: no space left on device, write': 'disk',+ 'ổ đĩa còn 1.2 GB, cần ≥ 5.0 GB': 'disk',+ 'Claude Code quá giờ (25 phút)': 'timeout',+ 'phân tích lỗi: Library cublas64_12.dll is not found or cannot be loaded': 'cuda',+ 'server khởi động lại khi job đang chạy': 'interrupted',+ 'Overloaded (529)': 'overloaded',+ 'không nghe được lời nào trong video': 'no_speech',+};+for (const [msg, code] of Object.entries(WHY)) ok(explain(msg) === code, `explain → ${code}`, `${explain(msg)} ← ${msg}`);+ok(explain('một lỗi lạ chưa ai gặp xyz') === null, 'explain lỗi lạ → null (UI hiện nguyên văn)');+ok(explain('HyperFrames render lỗi (mã 1)', ['render 40% capture 401/600']) === 'scene_invalid', 'explain không nhầm 401/600 khung là lỗi 401');++// ---- 3. đọc đuôi + nhật ký job (thư mục tạm, không đụng jobs/ thật) ----+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'logs-check-'));+try {+ const jd = path.join(tmp, 'jobs'); const ed = path.join(tmp, 'edits');+ fs.mkdirSync(path.join(jd, 'j1'), { recursive: true }); fs.mkdirSync(path.join(ed, 'e1'), { recursive: true });+ const many = Array.from({ length: 500 }, (_, i) => `[10:00:${String(i % 60).padStart(2, '0')}] dòng ${i}`);+ many.push('[10:01:00] trạng thái → generating', `[10:01:01] gọi API với ANTHROPIC_API_KEY=sk-ant-api03-secretsecretsecret123`, `[10:01:02] đọc ${path.join(home, 'secret.txt')}`, '[10:01:03] trạng thái → error: API 401 AuthenticationError');+ fs.writeFileSync(path.join(jd, 'j1', 'log.txt'), many.join('\n') + '\n');+ const tf = tailFile(path.join(jd, 'j1', 'log.txt'));+ ok(tf.lines.length === 300 && tf.truncated && tf.total === 504, 'tailFile 300 dòng cuối', JSON.stringify({ n: tf.lines.length, t: tf.total }));+ const ctx = { jobsDir: jd, editsDir: ed, readJob: (id) => (id === 'j1' ? { id, status: 'error', error: 'API 401 AuthenticationError sk-ant-api03-secretsecretsecret123', templateId: '009' } : null),+ readEdit: (id) => (id === 'e1' ? { id, status: 'error', step: 'phân tích', error: 'phân tích lỗi: CUDA failed', sourceName: 'clip.mp4' } : null) };+ const v = jobLog('job', 'j1', ctx);+ const all = JSON.stringify(v);+ ok(v && v.failed && v.step === 'generating' && v.why === 'api_key', 'jobLog: bước hỏng + mã lỗi', JSON.stringify({ step: v?.step, why: v?.why }));+ ok(!all.includes('secretsecret') && !all.toLowerCase().includes(home.toLowerCase().replace(/\\/g, '\\\\')), 'jobLog không lộ khoá / đường dẫn nhà');+ ok(!logText(v).includes('secretsecret'), 'file .txt không lộ khoá');+ const e = jobLog('edit', 'e1', ctx);+ ok(e && e.step === 'phân tích' && e.why === 'cuda', 'jobLog edit: bước + mã lỗi CUDA', JSON.stringify({ step: e?.step, why: e?.why }));+ for (const bad of ['..', '../jobs', '..\\j1', 'j1/../j1', '', 'a'.repeat(81), 'j1.', '%2e%2e']) ok(jobLog('job', bad, ctx) === null, `jobLog chặn id "${bad.slice(0, 12)}"`);+} finally { fs.rmSync(tmp, { recursive: true, force: true }); }++// ---- 4. HTTP trên server đang chạy (chỉ GET) ----+const port = Number(process.argv[2]);+function get(p, headers = {}, method = 'GET') {+ return new Promise((resolve) => {+ const req = http.request({ host: '127.0.0.1', port, path: p, method, headers: { Host: `127.0.0.1:${port}`, ...headers } }, (res) => {+ let b = ''; res.setEncoding('utf8'); res.on('data', (c) => { b += c; }); res.on('end', () => resolve({ code: res.statusCode, headers: res.headers, body: b }));+ });+ req.on('error', (e) => resolve({ code: 0, body: e.message }));+ req.end();+ });+}+if (port) {+ const s = await get('/api/logs/server');+ ok(s.code === 200 && Array.isArray(JSON.parse(s.body).lines), 'GET /api/logs/server 200');+ ok(!/sk-ant-[A-Za-z0-9]{10}/.test(s.body) && !s.body.toLowerCase().includes(home.toLowerCase().replace(/\\/g, '\\\\')), 'log server không lộ khoá / đường dẫn nhà');+ for (const p of ['/api/logs/job/..', '/api/logs/job/..%2F..%2Fpackage.json', '/api/logs/job/%2e%2e', '/api/logs/edit/..%5C..%5Cserver', '/api/logs/job/a%2Fb', '/api/logs/job/' + 'x'.repeat(81), '/api/logs/job/x.y', '/api/logs/foo/abc', '/api/logs/job/../../package.json']) {+ const r = await get(p);+ ok([400, 404].includes(r.code) && !r.body.includes('"version"') && !r.body.includes('"lines"'), `chặn ${p.slice(0, 44)} → ${r.code}`);+ }+ const nf = await get('/api/logs/job/khong-co-job-nay');+ ok(nf.code === 404, 'job không có → 404');+ const evil = await get('/api/logs/server', { Origin: 'http://evil.example' });+ ok(evil.code === 403, 'Origin lạ → 403', String(evil.code));+ const own = await get('/api/logs/server', { Origin: `http://127.0.0.1:${port}` });+ ok(own.code === 200, 'Origin của app → 200');+ const post = await get('/api/logs/server', {}, 'POST');+ ok(post.code === 403 || post.code === 405, 'POST → bị từ chối (chỉ đọc)', String(post.code));+ const del = await get('/api/logs/job/abc', {}, 'DELETE');+ ok([403, 405].includes(del.code), 'DELETE → bị từ chối', String(del.code));+ const rebind = await get('/api/logs/server', { Host: 'evil.example' });+ ok(rebind.code === 421, 'Host lạ (DNS rebinding) → 421');+ // 1 job lỗi có thật (nếu có): mã lỗi + tải .txt+ const jobs = JSON.parse((await get('/api/jobs')).body);+ const bad = jobs.find((j) => j.status === 'error');+ if (bad) {+ const r = await get('/api/logs/job/' + bad.id);+ const v = JSON.parse(r.body);+ ok(r.code === 200 && v.failed && v.lines.length > 0, `nhật ký job lỗi ${bad.id}: ${v.why || 'không mã'} · bước ${v.step}`);+ const d = await get('/api/logs/job/' + bad.id + '?download=1');+ ok(d.code === 200 && /attachment; filename="lumreels-job-[\w-]+-log\.txt"/.test(d.headers['content-disposition'] || '') && /^text\/plain/.test(d.headers['content-type']), 'tải .txt có Content-Disposition');+ } else console.log('(không có job lỗi để thử tải .txt)');+ const eds = JSON.parse((await get('/api/edits')).body);+ if (eds[0]) { const r = await get('/api/logs/edit/' + eds[0].id); ok(r.code === 200 && Array.isArray(JSON.parse(r.body).lines), 'nhật ký edit 200'); }+}++console.log(`\n${pass} PASS, ${fail} FAIL`);+process.exit(fail ? 1 : 0);