Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.
Editor: a failed step says what went wrong and offers the diagnostic report
Bowen Xuea2f2eedd0bdf
diff --git a/web/editor.css b/web/editor.cssindex 79cb4b0..ed5584c 100644--- a/web/editor.css+++ b/web/editor.css@@ -67,6 +67,12 @@.fv-ed-genbar[data-mode=selected] .fv-ed-gen-hint{flex:none}.fv-ed-gen-note{font-size:13px;color:var(--fv-ink);flex:0 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.fv-ed-gen-note[hidden]{display:none}+.fv-editor:has(.fv-ed-gen-failure:not([hidden])){--fv-ed-generation-row:max-content}+.fv-ed-genbar:has(.fv-ed-gen-failure:not([hidden])){flex-wrap:wrap;padding-top:10px;padding-bottom:10px}+.fv-editor .fv-ed-gen-failure{display:block;flex:1 0 100%;min-width:0}+.fv-ed-failure-actions{justify-content:flex-start;width:100%}+.fv-ed-failure-reason{flex:1 1 220px;min-width:0;color:var(--fv-warning);overflow-wrap:anywhere}+.fv-ed-gen-failure .fv-report-tip{width:100%}.fv-ed-basic-progress[data-state=waiting] .fv-ed-basic-percent{font-weight:500;color:var(--fv-muted)}.fv-ed-description{flex:1;width:0}.fv-ed-first-frame{display:flex;align-items:center;gap:8px;flex:none;font-size:13px;white-space:nowrap}@@ -164,6 +170,7 @@/* Keep the editor's controls visible instead of clipping them at phone widths. */@media(max-width:480px){.fv-studio.fv-editor{grid-template-rows:auto minmax(96px,1fr) 40px var(--fv-ed-generation-row,max-content) auto minmax(160px,236px)}+ .fv-studio.fv-editor:has(.fv-ed-gen-failure:not([hidden])){grid-template-rows:auto minmax(0,1fr) 40px var(--fv-ed-generation-row,max-content) auto minmax(160px,236px)}.fv-studio.fv-editor .fv-header:has(.fv-view-switch){grid-template-columns:minmax(0,1fr) auto}.fv-ed-toolbar{display:grid;grid-template-columns:auto minmax(0,1fr);height:auto;gap:4px 8px;padding:4px 12px;overflow:visible}.fv-ed-toolbar>.fv-ed-tool-group:nth-child(2){grid-column:2;grid-row:1/3;flex-wrap:wrap;align-self:start;min-width:0}diff --git a/web/editor.js b/web/editor.jsindex eacb1a8..2efdc99 100644--- a/web/editor.js+++ b/web/editor.js@@ -23,13 +23,52 @@ import {createSelectionActions, deletionStatus, isMultiple, isTyping, playheadIdimport {isolateDialogKeys, topDialog} from './dialog_keys.js';import {createBlockNotes, describedTrack} from './editor_notes.js';import {createFirstRunGuide} from './first_run_guide.js';-const editorStyles = Promise.all(['editor.css', 'editor_tracks.css', 'editor_frame.css', 'editor_adjust.css', 'editor_adjust_picture.css', 'editor_preview_picture.css', 'editor_select.css', 'editor_menu.css', 'editor_text.css', 'editor_notes.css', 'editor_transport.css'].map(name => {+import {createEditorFailures} from './editor_failure.js';+const editorStyles = Promise.all(['result_actions.css', 'editor.css', 'editor_tracks.css', 'editor_frame.css', 'editor_adjust.css', 'editor_adjust_picture.css', 'editor_preview_picture.css', 'editor_select.css', 'editor_menu.css', 'editor_text.css', 'editor_notes.css', 'editor_transport.css'].map(name => {const style = document.createElement('link'); style.rel = 'stylesheet'; style.href = new URL(name, import.meta.url).href;const ready = 'sheet' in style ? new Promise(resolve => { style.onload = style.onerror = resolve; }) : Promise.resolve();document.head.append(style); return ready;}));const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };const language = () => new URLSearchParams(location.search).get('freevideo_lang') || navigator.language;+// Shared by error() and actions.reasonText: one sentence naming the failed step.+export function editorErrorText(value, t = en => en) {+ const oneLine = value => typeof value === 'string' ? value.trim().split(/[\r\n]+/).find(line => line.trim())?.trim() || '' : '';+ const detail = value?.detail || (value?.error && typeof value.error === 'object' ? value.error : value);+ const raw = [detail?.response?.error?.message, detail?.response?.error, detail?.response?.message,+ detail?.exception_message, detail?.message, value?.error?.message, value?.error, value].map(oneLine).find(Boolean) || '';+ const code = value?.code || detail?.code || value?.reason || detail?.reason || raw;+ const node = oneLine(detail?.node_type), step = `${value?.phase || ''} ${value?.stage || ''} ${node}`;+ const part = Number.isInteger(value?.index) ? value.index + 1 : null;+ const generating = part ? t(`Generating part ${part}`, `生成第 ${part} 段`) : t('Generation', '生成');+ const stage = /encod|编码/i.test(step) ? t('Encoding', '编码') : /decod|解码/i.test(step) ? t('Decoding', '解码')+ : /load|model|加载/i.test(step) ? t('Loading the model', '加载模型') : generating;+ if (code === 'gpu_memory' || /out of memory|cuda.*memory|显存不足|显存不够/i.test(raw))+ return t(`${stage} ran out of GPU memory`, `${stage}时显存不足`);+ const known = {+ chain_part_too_short: t('Each continued part must be at least 10 seconds.', '续接的每一段至少要 10 秒。'),+ chain_too_long: t('A video can have up to 5 parts.', '一条视频最多 5 段。'),+ too_long: t('This part is longer than the maximum length. Shorten it and try again.', '这一段超过了最长时长,请缩短后再试。'),+ missing_node: t('Generation is not ready. Restart FreeVideo.', '生成功能没有就绪,请重新启动 FreeVideo。'),+ chain_missing: t('Generation could not be submitted. Choose "Generate" again.', '提交生成时出错,请再点一次“生成”。'),+ result_mismatch: t('Reading the result failed. Choose "Generate" again.', '读取生成结果时出错,请再点一次“生成”。'),+ no_material: t('The media this part uses is missing.', '找不到这一段用到的素材。'),+ };+ if (known[code]) return known[code];+ if (['model_missing', 'missing_model', 'model_not_found'].includes(code) || /(?:model|checkpoint|模型).*(?:not found|missing|不存在|缺失)/i.test(raw))+ return t(`Loading the model failed: ${raw || code}`, `加载模型时出错:${raw || code}`);+ if (['timeout', 'timed_out', 'generation_timeout'].includes(code) || /timed?\s*out|timeout|超时/i.test(raw))+ return t(`${stage} timed out`, `${stage}时等待超时`);+ const received = raw || (/^[a-z_]+$/.test(code) ? '' : code);+ return received ? t(`${generating} failed: ${received}`, `${generating}时出错:${received}`)+ : t(`${generating} failed`, `${generating}时出错`);+}+function exportErrorText(value, t) {+ const message = [value?.response?.error?.message, value?.response?.error, value?.response?.message, value?.message]+ .find(text => typeof text === 'string' && text.trim() && text !== 'editor_request')?.trim().split(/[\r\n]+/)[0];+ // A bare status code means nothing to the user; the server's own words do.+ return message ? t(`Export failed: ${message}`, `导出时出错:${message}`) : t('Export failed. Try again.', '导出时出错,请再试一次。');+}function restoreGeneration(record, before, prepared) {const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);const entries = value => new Map(value.tracks.flatMap(track => track.clips.map(clip => [clip.id, {track: track.id, clip}])));@@ -127,10 +166,11 @@ export function openEditor({api, app, from = null, panel = {}, components: givendrawer.setAttribute('aria-expanded', 'false');const exportBox = el('div', 'fv-ed-export-box'), exportHint = el('span', 'fv-ed-export-hint'), exportButton = button(t('Export', '导出'), async () => {try {+ if (explainExport()) return;if (exportStatus?.state === 'done' && exportMatches()) { await actions.export(); return; }const options = await openExportDialog({parent: element, state, sources: store.sources, t, onError: error});if (options && !disposed) await actions.export(options);- } catch (value) { error(value); }+ } catch (value) { error(value, 'export'); }}, 'fv-primary');const exportCancel = button('', () => store.cancelExport(exportStatus.id).catch(error)); exportCancel.hidden = true; exportCancel.append(icon('m4 4 8 8M12 4l-8 8')); exportCancel.setAttribute('aria-label', t('Cancel', '取消'));exportBox.append(exportHint, exportButton, exportCancel); brand.append(wordmark(), title);@@ -161,8 +201,10 @@ export function openEditor({api, app, from = null, panel = {}, components: givenlet library = null, closing = false, closePromise = null, exportSnapshot = null, lastSeed = null, projectEpoch = 0;let disposed = false, suppressSave = false, savedContent = '', initializing = true, tracks = null, genbar = null, adjustPanel = null, exportStatus = null, pointerEditing = false, deferredStamp = null;let capability = {maxSeconds: 15, maxFollowSeconds: 15, maxRequestFrames: null, estimate: () => null}, generationBusy = false, switching = false, generationDone = null, finishGeneration = null;- let noticeTimer = null, stopExport = null, mostRecentJob = null, guide = null;+ let noticeTimer = null, stopExport = null, mostRecentJob = null, exportPreparing = false, guide = null;const jobWatchers = new Map(), progress = new Map(), jobStatuses = new Map(), runProgress = new Map();+ const failures = createEditorFailures({api, state, jobStatuses, reasonText: value => editorErrorText(value, t)});+ let submissionFailure = null;let blockStates = null, progressObserver = null, progressConnection = null;function barJob(job) {const latest = [...runProgress.values()].filter(message => message.chain.id === job.id)@@ -190,21 +232,29 @@ export function openEditor({api, app, from = null, panel = {}, components: givenif (message.prompt_id && block.prompt_id && message.prompt_id !== block.prompt_id) return false;if (previous?.prompt_id === message.prompt_id && previous?.stream_id === message.stream_id&& Number.isFinite(previous?.sequence) && previous.sequence >= message.sequence) return true;+ failures.receive(job, block, message);runProgress.set(key, message); paintJob(job);+ if (model.attemptClip(state.record, block.id)?.pending === 'failed') tracks?.refresh?.();if (mostRecentJob === job.id) genbar?.update(barJob(job));return true;}const content = record => JSON.stringify({...record, id: null, revision: 0});function notify(text) { if (disposed) return; notice.textContent = text; notice.hidden = false; clearTimeout(noticeTimer); noticeTimer = setTimeout(() => { notice.hidden = true; }, 9000); }- function error(value) {- const code = value?.code || value?.message;+ // `step` names what was being done, so a failure there says which step went wrong.+ function error(value, step = null) {+ const code = value?.reason || value?.code || value?.message;+ if (['missing_glyphs', 'MissingGlyphs', 'source_missing'].includes(code)) {+ notify(code === 'source_missing' ? t('A source file is missing. Import it again from the library.', '有素材的原文件找不到了,请在素材库重新导入。')+ : t('The chosen font is missing some characters. Choose another font.', '所选字体缺少部分字符,请换一种字体。'));+ return {ok: false, reason: code};+ }if (['audio_prepare', 'speed_pending', 'speed_locked', 'speed'].includes(code)) return {ok: false, reason: code};if (code === 'unsupported') { genbar?.update(null); return; }if (['chain_too_long', 'chain_part_too_short'].includes(code)) {const [en, zh] = (value.said || []).map(text => typeof text === 'string' && text ? text.slice(0, 200) : null);- notify(code === 'chain_too_long' ? t(en || 'This video can have up to 5 parts. Make it shorter.', zh || '这条视频最多 5 段,请缩短一些。')- : t(en || 'Each continued part must be at least 10 seconds. Make it longer.', zh || '接着生成的每一段至少 10 秒,请加长一些。'));- return {ok: false, reason: code};+ const text = code === 'chain_too_long' ? t(en || 'This video can have up to 5 parts. Make it shorter.', zh || '这条视频最多 5 段,请缩短一些。')+ : t(en || 'Each continued part must be at least 10 seconds. Make it longer.', zh || '接着生成的每一段至少 10 秒,请加长一些。');+ notify(text); return {ok: false, reason: code, say: text};}if (['busy', 'locked', 'text', 'audio_full', 'overlap', 'range'].includes(code)) {if (['locked', 'audio_full', 'overlap', 'range'].includes(code)) tracks?.flashBlocked?.(value.displayFrame);@@ -214,7 +264,8 @@ export function openEditor({api, app, from = null, panel = {}, components: givenif (said) notify(said);return {ok: false, reason: code};}- notify(t('Could not complete. Try again.', '没有完成,请重试'));+ const text = step === 'generate' ? editorErrorText(value, t) : step === 'export' ? exportErrorText(value, t) : t('Could not complete. Try again.', '没有完成,请重试');+ notify(text); return {ok: false, reason: code, say: text};}const store = createEditorStore(api, {t, notify, standIn: given?.generationStandIn, onGenerationReady: ready => {if (disposed) return;@@ -323,16 +374,19 @@ export function openEditor({api, app, from = null, panel = {}, components: givenreturn found ? {text: found.text, before: false} : null;}const markHeld = (ids, queued) => { for (const id of ids) tracks?.setProgress(id, {state: 'waiting', fraction: 0, remainingSeconds: null, ...(queued ? {queued: true} : {})}); };- function hold(selection, text) {+ const queuedReady = () => t('Queued. It starts once generation is ready.', '已排队,准备好后自动开始。');+ function hold(selection, text, job = null) {const range = selectionRange(selection), selectedIds = selectionClips(selection).map(clip => clip.id), shown = selection === state.selection;let ids = [];- state.apply(t('Generate', '生成'), record => {+ if (job) ids = selectedIds;+ else state.apply(t('Generate', '生成'), record => {const selected = selectedIds.map(id => model.find(record, id)).filter(Boolean), planned = selected.length && selected.every(clip => !clip.source && clip.pending && !generating(clip));const next = planned ? model.startAttempt(record, selected.map(clip => clip.id), text) : model.planRange(record, {...range, target: 'both', text, maxSeconds: capability.maxSeconds, maxFollowSeconds: capability.maxFollowSeconds});ids = next.tracks[0].clips.filter(clip => clip.start >= range.start && clip.start < range.start + range.frames && clip.pending && !generating(clip)).map(clip => clip.id);return next;}, {checkpoint: true});- held.push({ids, text}); markHeld(ids, true);+ if (!ids.every(isHeld)) held.push({ids, text, job});+ markHeld(ids, true);if (shown) state.select({kind: 'clip', ids});rememberView();}@@ -341,6 +395,14 @@ export function openEditor({api, app, from = null, panel = {}, components: givenstartingHeld = true;try {while (held.length && !disposed) {+ if (generationBusy || !store.generationAvailable || closing) break;+ if (held[0].job) {+ const entry = held.shift(); markHeld(entry.ids, false);+ if (entry.ids.some(id => model.find(state.record, id)?.job === entry.job)) {+ try { await actions.resume(entry.job); } catch (value) { error(value, 'generate'); }+ }+ continue;+ }const entry = held[0], clips = entry.ids.map(id => model.find(state.record, id)).filter(clip => clip && clip.pending && !generating(clip));if (!clips.length) { held.shift(); markHeld(entry.ids, false); rememberView(); continue; }const selection = {kind: 'clip', ids: clips.map(clip => clip.id)}, before = partBefore(Math.min(...clips.map(clip => clip.start)));@@ -348,7 +410,7 @@ export function openEditor({api, app, from = null, panel = {}, components: givenheld.shift(); markHeld(entry.ids, false); rememberView();if (before && !before.source && before.pending) { genbar?.say(t('The part before did not finish, so this one did not start.', '上一段没有完成,这一段没有开始。')); continue; }try { await actions.generate({text: entry.text, selection}); }- catch (value) { const reason = error(value); if (reason && !['chain_too_long', 'chain_part_too_short'].includes(reason.reason)) genbar?.say(t('This part did not start. Choose "Generate" again.', '这一段没有开始,请再点一次“生成”。')); }+ catch (value) { const reason = error(value, 'generate'); if (reason && !['chain_too_long', 'chain_part_too_short'].includes(reason.reason)) genbar?.say(reason.say); }}} finally { startingHeld = false; }}@@ -356,12 +418,38 @@ export function openEditor({api, app, from = null, panel = {}, components: givenreturn store.getSources(model.references(state.record).map(sourceKey)).then(() => { player.refresh(); tracks?.refresh?.(); });}const exportMatches = () => exportSnapshot && exportSnapshot.id === state.record.id && exportSnapshot.revision === state.record.revision && exportSnapshot.content === content(state.record);+ function explainExport() {+ if (initializing || switching) { notify(t('Opening the edit…', '正在打开…')); return true; }+ if (exportPreparing || ['running', 'queued'].includes(exportStatus?.state)) {+ notify(t('Exporting. You can export again when it finishes.', '正在导出,完成后可以再导出一次。'));+ exportBox.scrollIntoView?.({block: 'nearest'}); exportButton.focus({preventScroll: true}); return true;+ }+ if (!model.exportFrames(state.record)) { notify(t('The timeline is empty. Add a clip first.', '时间线是空的,请先放入素材。')); return true; }+ return false;+ }+ async function saveForExport(epoch) {+ await queue.flush();+ for (let retry = 0; queue.dirty && retry < 3; retry++) {+ await new Promise(resolve => setTimeout(resolve, 200));+ if (disposed || closing || epoch !== projectEpoch) return false;+ await queue.flush();+ }+ if (disposed || closing || epoch !== projectEpoch) return false;+ if (queue.dirty) {+ notify(t('Changes could not be saved after three tries. Check disk space, then export again.', '改动没有保存成功,已重试三次。请检查磁盘空间后再导出。'));+ return false;+ }+ return !!state.record.id;+ }function updateTop() {title.replaceChildren(el('span', '', state.record.name || new Date().toLocaleDateString()), icon('m4 6 4 4 4-4')); title.title = state.record.name;exportButton.classList.toggle('fv-primary', !!model.exportFrames(state.record) && !state.selection && !jobActive() && !exportStatus);- if (exportStatus?.state === 'done') exportButton.textContent = exportMatches() ? t('View', '查看') : t('Export', '导出');- exportButton.disabled = initializing || !model.exportFrames(state.record) || switching || ['running', 'queued'].includes(exportStatus?.state);- exportButton.title = '';+ const running = exportPreparing || ['running', 'queued'].includes(exportStatus?.state);+ if (['running', 'queued'].includes(exportStatus?.state)) exportButton.textContent = t(`Export ${Math.round((exportStatus.fraction || 0) * 100)}%`, `导出 ${Math.round((exportStatus.fraction || 0) * 100)}%`);+ else if (exportPreparing) exportButton.textContent = queue.dirty ? t('Saving changes…', '正在保存改动…') : t('Exporting', '正在导出');+ else exportButton.textContent = exportStatus?.state === 'done' && exportMatches() ? t('View', '查看') : t('Export', '导出');+ // Never disabled: a press that cannot export says why next to it.+ exportButton.disabled = false; exportButton.title = '';}async function snapshot() {let value = panel.snapshot ? structuredClone(await panel.snapshot()) : structuredClone(await app.graphToPrompt());@@ -386,6 +474,7 @@ export function openEditor({api, app, from = null, panel = {}, components: givenconst previous = jobStatuses.get(job.id);if (Number.isFinite(previous?.updated) && job.updated < previous.updated)return ['queued', 'running', 'cancelling'].includes(previous.state);+ failures.reconcile(job, previous);mostRecentJob = job.id; jobStatuses.set(job.id, job); paintJob(job);const completed = new Set();for (const block of job.blocks || []) {@@ -412,7 +501,8 @@ export function openEditor({api, app, from = null, panel = {}, components: givenerror(value);}} else if (block.state === 'failed') {- const reason = /^[a-z_]{1,80}$/.test(block.error || '') ? block.error : 'generation_failed';+ const cause = block.reason || block.error;+ const reason = /^[a-z_]{1,80}$/.test(cause || '') ? cause : 'generation_failed';state.settle(record => model.fail(record, block.id, reason, job.id));} else if (['cancelled', 'interrupted'].includes(block.state) || (['cancelled', 'interrupted', 'failed'].includes(job.state) && block.state === 'pending')) {state.settle(record => pinStoppedJob(record, [block.id], job.id));@@ -460,8 +550,8 @@ export function openEditor({api, app, from = null, panel = {}, components: givenif (!remembered) try { remembered = JSON.parse(localStorage.getItem(viewPrefix + viewKey)); } catch {}initialSelection = offerInitial = extendEntry = null;projectEpoch++; held.length = 0;- player.pause(); for (const stop of jobWatchers.values()) stop(); jobWatchers.clear(); jobStatuses.clear(); progress.clear(); runProgress.clear(); progressConnection?.reset();- mostRecentJob = null; genbar?.update(null); queue.reset(record); stopExport?.(); stopExport = null; exportStatus = exportSnapshot = null; exportButton.textContent = t('Export', '导出');+ player.pause(); for (const stop of jobWatchers.values()) stop(); jobWatchers.clear(); jobStatuses.clear(); progress.clear(); runProgress.clear(); failures.clear(); progressConnection?.reset();+ mostRecentJob = null; submissionFailure = null; genbar?.update(null); queue.reset(record); stopExport?.(); stopExport = null; exportStatus = exportSnapshot = null; exportButton.textContent = t('Export', '导出');suppressSave = true; try { state.replace(record); savedContent = content(record); } finally { suppressSave = false; }const width = tracksHost.clientWidth - 148; if (width > 0) state.setZoom(width / 90);tracks?.setScrollLeft(0);@@ -540,6 +630,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given}const actions = {error, editError: error, notify, sources: store.sources, waveform: key => store.waveform(key), mediaURL: value => mediaURL(api, value),+ projectToken: () => initializing ? null : projectEpoch,togglePlay: () => player.toggle(),pause: () => player.pause(),async previewSource(source) {@@ -578,7 +669,19 @@ export function openEditor({api, app, from = null, panel = {}, components: givenreturn {ok: false, reason: valueError.code};}},- reasonText: code => code === 'gpu_memory' ? t('Not enough graphics memory', '显存不够') : t('Could not generate', '没能生成'),+ reasonText: value => editorErrorText(value, t),+ failureText: id => failures.text(id),+ selectedFailure() {+ const clip = state.selection?.kind === 'clip' && state.record.tracks.flatMap(track => track.clips).find(clip => state.selection.ids.includes(clip.id) && clip.pending === 'failed');+ if (clip) return {id: clip.id, text: failures.text(clip.id)};+ return submissionFailure === JSON.stringify(state.selection) ? {id: 'submission', text: failures.text('submission')} : null;+ },+ async downloadFailure(id) {+ if (disposed || id !== 'submission' && !model.find(state.record, id)) return;+ if (id !== 'submission') state.select({kind: 'clip', ids: [id]});+ await genbar.downloadFailure(actions.selectedFailure()?.id || id);+ },+ downloadFailureReport: (id, options) => failures.download(id, options),supportedSelection(selection = state.selection) {if (selection?.kind === 'clip' && selection.ids.some(id => isText(model.find(state.record, id)))) return false;const range = selectionRange(selection); if (!range) return false;@@ -628,14 +731,15 @@ export function openEditor({api, app, from = null, panel = {}, components: givenasync generate({target = 'both', text = '', label = t('Generate', '生成'), selection = state.selection} = {}) {if (target !== 'both' || !actions.supportedSelection(selection)) throw new model.EditError('unsupported');if (!actions.canGenerate(text, selection)) throw new model.EditError('text');+ submissionFailure = null; genbar?.update(null);const shown = selection === state.selection;generationBusy = true; updateTop(); updateTransport();generationDone = new Promise(resolve => { finishGeneration = resolve; });- let ids = [], prepared = null, beforeAttempt = null, priorSelection = null, priorText = null, submittedSelection = null;+ let ids = [], prepared = null, beforeAttempt = null, priorSelection = null, priorText = null, submittedSelection = null, frozen = null;const epoch = projectEpoch, range = selectionRange(selection), selectedIds = selectionClips(selection).map(clip => clip.id);sendingRanges.add(range);try {- const frozen = await snapshot(); if (epoch !== projectEpoch || closing || disposed || !store.generationAvailable) return;+ frozen = await snapshot(); if (epoch !== projectEpoch || closing || disposed || !store.generationAvailable) return;beforeAttempt = state.record; priorSelection = state.selection; priorText = state.rangeText;state.apply(label, record => {const selected = selectedIds.map(id => model.find(record, id)).filter(Boolean), alreadyPlanned = selected.length && selected.every(clip => !clip.source && clip.pending && !['queued', 'running'].includes(clip.pending));@@ -682,9 +786,14 @@ export function openEditor({api, app, from = null, panel = {}, components: givenif (epoch !== projectEpoch) return;state.settle(record => model.assignJob(record, ids, job.id, {prepared}));queue.enqueue(state.record);+ failures.remember(job, frozen);mostRecentJob = job.id; jobStatuses.set(job.id, job); genbar.update(job); watchJob(job.id);} catch (value) {- if (ids.length && epoch === projectEpoch) state.settle(record => model.settle(record, ids, 'draft'));+ if (epoch === projectEpoch) {+ if (ids.length) state.settle(record => model.settle(record, ids, 'draft'));+ failures.submission(value, frozen, text);+ submissionFailure = JSON.stringify(state.selection); genbar?.update(null);+ }throw value;} finally { sendingRanges.delete(range); for (const id of ids) sending.delete(id); if (disposed && ids.length) queue.enqueue(state.record); generationBusy = false; finishGeneration?.(); generationDone = null; finishGeneration = null; updateTop(); updateTransport(); startHeld(); }},@@ -713,7 +822,7 @@ export function openEditor({api, app, from = null, panel = {}, components: givenconst waiting = waitingFor(selection);if (waiting) {hold(selection, text);- return {text, say: [said, used, waiting === 'ready' ? t('Queued. It starts once generation is ready.', '已排队,准备好后自动开始。')+ return {text, say: [said, used, waiting === 'ready' ? queuedReady(): t('Queued. It starts after the part before it.', '已排队,上一段完成后自动开始。')].filter(Boolean).join(' '), queued: true};}const busyBefore = jobActive();@@ -739,16 +848,28 @@ export function openEditor({api, app, from = null, panel = {}, components: givenif (!own && actions.selectionSending()) return;const id = own || mostRecentJob; if (id) await deliverChain(await store.chainAction(id, 'cancel'));},- async resume() {- if (!store.generationAvailable) return;+ async resume(jobId = null) {const epoch = projectEpoch;- const id = mostRecentJob || selectionClips().find(clip => clip.job)?.job; if (!id) return;+ const id = jobId || mostRecentJob || selectionClips().find(clip => clip.job)?.job; if (!id) return;+ if (!store.generationAvailable) {+ const ids = state.record.tracks[0].clips.filter(clip => clip.job === id && clip.pending).map(clip => clip.id);+ hold({kind: 'clip', ids}, '', id); genbar?.say(queuedReady());+ if (genHost.hidden) notify(queuedReady());+ void startHeld(); return;+ }const job = await store.chainAction(id, 'resume'); if (epoch !== projectEpoch || disposed) return;for (const block of job?.blocks || []) if (block.state !== 'done') runProgress.delete(`${id}:${block.id}`);const ids = state.record.tracks[0].clips.filter(clip => clip.job === id && clip.pending).map(clip => clip.id);state.settle(record => model.settle(record, ids, 'queued')); if (job) { await deliverChain(job); watchJob(id); }},- async retry(id) { if (!store.generationAvailable) return; state.select({kind: 'clip', ids: [id]}); const clip = model.find(state.record, id); if (clip.job) { mostRecentJob = clip.job; await actions.resume(); } else await actions.generate({text: clip.text || panel.text || ''}); },+ async retry(id) {+ state.select({kind: 'clip', ids: [id]}); const clip = model.find(state.record, id); if (!clip) return;+ if (clip.job) { mostRecentJob = clip.job; await actions.resume(); }+ else if (!store.generationAvailable) {+ if (!actions.selectionHeld()) hold(state.selection, clip.text || panel.text || '');+ genbar?.say(queuedReady()); if (genHost.hidden) notify(queuedReady()); void startHeld();+ } else await actions.generate({text: clip.text || panel.text || ''});+ },// Subtitles from speech hear the saved project, so it is saved first; a project never saved has nothing in it to hear.speech: {async start() {@@ -782,25 +903,30 @@ export function openEditor({api, app, from = null, panel = {}, components: givencancelDownload: () => store.cancelEarsPack(),},async export(options) {- if (['running', 'queued'].includes(exportStatus?.state)) return;+ if (explainExport()) return;if (exportStatus?.state === 'done' && exportMatches()) { await viewExport(exportStatus); return; }- if (!await textTools.beforeExport()) return;- await queue.flush();- if (queue.dirty) { return; }- if (!state.record.id) return;- exportSnapshot = {id: state.record.id, revision: state.record.revision, content: content(state.record)};- for (let attempt = 0; ; attempt++) {- try { exportStatus = await store.export(state.record.id, state.record.revision, options); break; }- catch (value) {- if (value.status !== 409 || attempt >= 2) throw value;- queue.enqueue(state.record); await queue.flush();- if (queue.dirty) return;- exportSnapshot = {id: state.record.id, revision: state.record.revision, content: content(state.record)};+ const epoch = projectEpoch; exportPreparing = true; updateTop();+ try {+ if (!await textTools.beforeExport()) return;+ if (!await saveForExport(epoch)) return;+ exportSnapshot = {id: state.record.id, revision: state.record.revision, content: content(state.record)};+ for (let attempt = 0; ; attempt++) {+ try {+ const status = await store.export(state.record.id, state.record.revision, options);+ if (disposed || closing || epoch !== projectEpoch) return;+ exportStatus = status; break;+ }+ catch (value) {+ if (value.status !== 409 || attempt >= 2) throw value;+ queue.enqueue(state.record);+ if (!await saveForExport(epoch)) return;+ exportSnapshot = {id: state.record.id, revision: state.record.revision, content: content(state.record)};+ }}- }- if (!exportStatus) return;- updateExport(exportStatus); stopExport?.();- stopExport = store.watchExport(exportStatus.id, updateExport);+ if (!exportStatus) return;+ updateExport(exportStatus); stopExport?.();+ stopExport = store.watchExport(exportStatus.id, updateExport);+ } finally { exportPreparing = false; updateTop(); }},};async function viewExport(value) {@@ -818,10 +944,14 @@ export function openEditor({api, app, from = null, panel = {}, components: givenif (exportSnapshot) exportSnapshot = {...exportSnapshot, id: value.project_id, revision: value.revision};exportStatus = value; const running = value.state === 'running' || value.state === 'queued';if (disposed) { if (!running) window.FreeVideoNotifyTaskDone?.({kind: 'export', id: value.id, ok: value.state === 'done'}); return running; }- exportButton.textContent = running ? t(`Export ${Math.round(value.fraction * 100)}%`, `导出 ${Math.round(value.fraction * 100)}%`) : value.state === 'done' && exportMatches() ? t('View', '查看') : t('Export', '导出');- exportCancel.hidden = !running; exportButton.disabled = running; exportButton.classList.remove('fv-primary');+ exportCancel.hidden = !running; updateTop(); exportButton.classList.remove('fv-primary');if (!running) {- if (value.state === 'failed') notify(t('Export did not finish', '导出没有完成'));+ if (value.state === 'failed') {+ if (['source_missing', 'missing_glyphs', 'MissingGlyphs'].includes(value.reason || value.code)) error(value);+ else notify(value.reason === 'disk_full' ? t('Export failed: the disk is full. Free some space, then export again.', '导出时出错:磁盘空间不够,空出空间后再导出。')+ : value.reason === 'unreadable' ? t('Export failed: a source file cannot be read. Import it again from the library.', '导出时出错:有素材读不出来,请在素材库重新导入。')+ : t('Export failed. Try again.', '导出时出错,请再试一次。'));+ }window.FreeVideoNotifyTaskDone?.({kind: 'export', id: value.id, ok: value.state === 'done'});}return running;@@ -839,8 +969,14 @@ export function openEditor({api, app, from = null, panel = {}, components: givencontrol.classList.add('fv-ed-icon');control.setAttribute('aria-label', label); return control;};- const toolUndo = toolButton(t('Undo', '撤销'), 'M5 4 2 7l3 3M2 7h7a4 4 0 0 1 0 8', () => state.undo(), 'fv-ed-undo fv-ed-icon', true);- const toolRedo = toolButton(t('Redo', '重做'), 'm11 4 3 3-3 3M14 7H7a4 4 0 0 0 0 8', () => state.redo(), 'fv-ed-redo fv-ed-icon', true);+ // Undo cannot take back a part while it generates; a press that changes nothing says so.+ function travel(back) {+ const before = content(state.record); back ? state.undo() : state.redo();+ if (content(state.record) === before && jobActive()) notify(back ? t('This part is generating. Undo once it finishes.', '这一段正在生成,完成后再撤销。')+ : t('This part is generating. Redo once it finishes.', '这一段正在生成,完成后再重做。'));+ }+ const toolUndo = toolButton(t('Undo', '撤销'), 'M5 4 2 7l3 3M2 7h7a4 4 0 0 1 0 8', () => travel(true), 'fv-ed-undo fv-ed-icon', true);+ const toolRedo = toolButton(t('Redo', '重做'), 'm11 4 3 3-3 3M14 7H7a4 4 0 0 0 0 8', () => travel(false), 'fv-ed-redo fv-ed-icon', true);const split = toolButton(t('Split', '剪开'), 'M6 5l8 8M6 11l8-8M6 4a2 2 0 1 1-4 0 2 2 0 0 1 4 0M6 12a2 2 0 1 1-4 0 2 2 0 0 1 4 0',() => selectionActions.run('b'), 'fv-ed-split');const remove = toolButton(t('Delete', '删除'), 'M2 4h12M6 4V2h4v2M4 4l1 10h6l1-10M7 6v5M9 6v5',@@ -962,7 +1098,7 @@ export function openEditor({api, app, from = null, panel = {}, components: givenif (handleSpeedKey(event)) return;if (key === ' ') { event.preventDefault(); player.toggle(); }else if (key === 'arrowleft' || key === 'arrowright') { event.preventDefault(); state.seek(Math.max(0, state.playhead + (key === 'arrowright' ? 1 : -1))); }- else if (mod && key === 'z') { event.preventDefault(); event.shiftKey ? state.redo() : state.undo(); }+ else if (mod && key === 'z') { event.preventDefault(); travel(!event.shiftKey); }}listen('keydown', keyboard); listen('keyup', event => event.stopPropagation());listen('cancel', event => {@@ -1040,7 +1176,7 @@ export function openEditor({api, app, from = null, panel = {}, components: givenlisteners.splice(0).forEach(remove => remove());for (const node of [element, ...element.querySelectorAll('*')]) for (const name of ['onclick', 'ondblclick', 'oninput', 'onchange', 'onkeydown', 'ondragstart']) node[name] = null;unsubscribe(); stopSources(); library?.dispose(); genbar.dispose(); tracks?.dispose(); stopExport?.();- progressConnection?.stop(); progressObserver?.disconnect(); runProgress.clear();+ progressConnection?.stop(); progressObserver?.disconnect(); runProgress.clear(); failures.clear();stopKeys();resumeCanvasPointer();window.removeEventListener('pagehide', leaving); clearTimeout(noticeTimer);@@ -1110,6 +1246,12 @@ export function openEditor({api, app, from = null, panel = {}, components: giventransportControls.attachTracks(tracks, module.snapFrame);if (api.addEventListener && api.removeEventListener) {progressConnection = createProgressConnection(api, receiveProgress); progressConnection.start();+ const executionError = event => {+ if (!failures.capture(event.detail)) return;+ tracks?.refresh?.(); genbar?.update(mostRecentJob ? barJob(jobStatuses.get(mostRecentJob)) : null);+ };+ api.addEventListener('execution_error', executionError);+ listeners.push(() => api.removeEventListener('execution_error', executionError));}if (panel.progressElement && typeof MutationObserver !== 'undefined') {progressObserver = new MutationObserver(() => { for (const job of jobStatuses.values()) paintJob(job); });diff --git a/web/editor_failure.js b/web/editor_failure.jsnew file mode 100644index 0000000..d778982--- /dev/null+++ b/web/editor_failure.js@@ -0,0 +1,86 @@+import {attemptClip, find} from './editor_model.js';+import {createErrorReport} from './error_panel.js';+import {saveReport, showReportTip, reportIssue} from './report_issue.js';+import {productVersion} from './updates.js';++// Receipts belong to an attempt, not to saved projects or undo history.+export function createEditorFailures({api, state, jobStatuses, reasonText}) {+ const details = new Map(), snapshots = new Map(), progress = new Map();+ let submissionError = null;+ const owns = (job, block) => attemptClip(state.record, block.id)?.job === job.id;+ const key = (job, block) => `${job.id}:${block.id}`;+ function receipt(id) {+ const clip = find(state.record, id) || (id === 'submission' && submissionError ? {id, text: submissionError.text} : null);+ if (!clip) return null;+ const job = jobStatuses.get(clip.job);+ // Redo can restore the original clip (including its audio partner).+ const owned = job?.blocks?.filter(block => owns(job, block)) || [];+ const block = owned.find(block => block.id === clip.id || block.id === clip.link)+ || owned.find(block => block.state === 'failed' && clip.part && block.part === clip.part);+ const live = block && progress.get(key(job, block));+ const current = live && (!block.prompt_id || live.prompt_id === block.prompt_id) ? live : null;+ const submission = id === 'submission' ? submissionError : null;+ const detail = details.get(block?.prompt_id || current?.prompt_id) || submission?.detail;+ const snapshot = snapshots.get(clip.job) || submission?.snapshot, index = job?.blocks?.indexOf(block);+ const value = {reason: block?.reason || current?.reason || clip.reason,+ error: block?.error || current?.error, detail,+ phase: current?.phase, stage: current?.stage, index: index >= 0 ? index : null};+ return {clip, job, block, snapshot, value, text: reasonText(value), attempt: `${clip.job || 'submission'}:${block?.prompt_id || block?.attempts || 0}`,+ reportId: [current?.report_id, block?.report_id].find(id => /^[a-f0-9]{32}$/.test(id || ''))};+ }+ function report(id) {+ const found = receipt(id); if (!found) return null;+ const {clip, job, block, snapshot, value} = found;+ const nodeId = snapshot?.node || job?.node || 'editor', original = snapshot?.prompt?.[nodeId];+ const detail = value.detail || (block?.error && typeof block.error === 'object' ? block.error : null) || {exception_message: block?.error || found.text,+ node_id: nodeId, node_type: original?.class_type || 'FreeVideoGenerate'};+ const inputs = {...original?.inputs, ...detail.current_inputs, ...block?.inputs,+ text: block?.inputs?.text ?? clip.text};+ return createErrorReport(detail, {stage: id === 'submission' ? 'submission' : 'execution', node: {id: nodeId},+ snapshot: {output: {...snapshot?.prompt, [nodeId]: {...original, inputs}}},+ progress: {phase: value.phase || clip.id, stage: value.stage || (value.index != null ? `Part ${value.index + 1}` : ''),+ ...(job ? {done: job.blocks.filter(block => block.state === 'done').length, total: job.blocks.length} : {})}});+ }+ return {+ remember(job, snapshot) { snapshots.set(job.id, snapshot); },+ reconcile(job, previous) {+ for (const block of job.blocks || []) {+ const old = previous?.blocks?.find(value => value.id === block.id), live = progress.get(key(job, block));+ if (old && (old.prompt_id !== block.prompt_id || old.attempts !== block.attempts)+ && live?.prompt_id === old.prompt_id) progress.delete(key(job, block));+ }+ },+ submission(error, snapshot, text) { submissionError = {detail: error, snapshot, text}; },+ capture(detail) {+ if (!detail?.prompt_id || typeof detail.prompt_id !== 'string') return false;+ for (const job of jobStatuses.values()) {+ if (!job.blocks?.some(block => owns(job, block) && (block.prompt_id === detail.prompt_id+ || !block.prompt_id && progress.get(key(job, block))?.prompt_id === detail.prompt_id))) continue;+ details.set(detail.prompt_id, structuredClone(detail)); return true;+ }+ return false;+ },+ receive(job, block, message) {+ const previous = progress.get(key(job, block));+ progress.set(key(job, block), {...(previous?.prompt_id === message.prompt_id ? previous : {}), ...message});+ },+ text(id) { return receipt(id)?.text || ''; },+ report,+ async download(id, {bar, anchor, t, current = () => true}) {+ const found = receipt(id); if (!found) return;+ let blob;+ if (found.reportId) {+ const response = await api.fetchApi(`/freevideo/report/${found.reportId}`);+ if (!response.ok) throw new Error(`HTTP ${response.status}`);+ blob = await response.blob();+ } else blob = new Blob([JSON.stringify(report(id), null, 2)], {type: 'application/json'});+ const latest = receipt(id);+ if (!current() || latest?.attempt !== found.attempt || latest?.value.detail !== found.value.detail) return;+ saveReport(blob);+ // Use exactly the video's card and submit flow, including no second download.+ return showReportTip(bar, anchor, t, {mode: 'downloaded',+ submit: () => reportIssue(() => Promise.resolve(blob), productVersion(), {save: false})});+ },+ clear() { details.clear(); snapshots.clear(); progress.clear(); submissionError = null; },+ };+}diff --git a/web/editor_genbar.js b/web/editor_genbar.jsindex 0a07aef..009c856 100644--- a/web/editor_genbar.js+++ b/web/editor_genbar.js@@ -18,6 +18,11 @@ export function createEditorGenbar(host, {state, t, actions, text = ''}) {host.append(hint, note, input, generate, cancel, resume);const firstFrame = createFirstFrameSwitch(host, {state, t, actions});input.after(firstFrame.element);+ const failure = el('div', 'fv-ed-gen-failure fv-result-links'), failureBar = el('div', 'fv-ed-failure-actions fv-actions');+ const failureReason = el('span', 'fv-ed-failure-reason'); failureReason.setAttribute('role', 'status');+ const report = el('button', 'fv-ed-failure-report fv-action fv-action-secondary', t('Download diagnostic report', '下载诊断报告')); report.type = 'button';+ failureBar.append(failureReason, report); failure.append(failureBar); failure.hidden = true; host.append(failure);+ let failureId = null, downloading = false;// Reference pictures for a part that starts fresh: thumbnails and a small "+" before the description.const references = actions.references ? createEditorReferences({t, source: actions.references.source, size: actions.references.size, error: actions.error, notify: actions.references.notify}) : null;if (references) input.before(references.element);@@ -25,6 +30,18 @@ export function createEditorGenbar(host, {state, t, actions, text = ''}) {// Which parts are generating, or how the job ended: a "Queued" line goes once this moves on.const progressKey = () => ['done', 'failed', 'cancelled', 'interrupted'].includes(status?.state) ? status.state: (status?.blocks || []).filter(block => block.state === 'running').map(block => block.id).join(',');+ async function downloadFailure(id = failureId) {+ if (disposed || downloading || id !== failureId) return;+ downloading = true; report.disabled = true;+ try {+ // A failed part offers its report on the part itself; the submit tip then hangs under this line's sentence.+ await actions.downloadFailureReport?.(id, {bar: failureBar, anchor: report.hidden ? failureReason : report, t,+ current: () => !disposed && failureId === id && !failure.hidden});+ } catch (value) {+ say(t(`Downloading the diagnostic report failed: ${value.message || value}`, `下载诊断报告时出错:${value.message || value}`));+ } finally { downloading = false; report.disabled = false; }+ }+ report.onclick = () => downloadFailure();function say(text, queued = false) {if (disposed) return;queuedAt = text && queued ? progressKey() : null;@@ -35,6 +52,15 @@ export function createEditorGenbar(host, {state, t, actions, text = ''}) {if (disposed) return;if (queuedAt != null && progressKey() !== queuedAt) say('');const current = ++serial, selection = previewSelection || state.selection;+ const selectedFailure = !previewSelection && actions.selectedFailure?.();+ if (failureId !== (selectedFailure?.id || null)) {+ failure.querySelector('.fv-report-tip')?.remove();+ failureId = selectedFailure?.id || null;+ }+ failure.hidden = !selectedFailure;+ failureReason.textContent = selectedFailure?.text || '';+ // Only a press that never became a part has no part to carry the report button.+ report.hidden = selectedFailure?.id !== 'submission';const running = ['queued', 'running', 'cancelling'].includes(status?.state);const selected = !!selection && (!!previewSelection || (actions.supportedSelection?.() ?? true));// While a part generates, choosing another place offers Generate again; it is queued behind.@@ -98,12 +124,13 @@ export function createEditorGenbar(host, {state, t, actions, text = ''}) {if (result?.say) say(result.say, !!result.queued);if (result?.focus) { pressing.delete(key); render(); input.disabled = false; input.focus(); }}- // A specific reason has already been said; a general one is added only when there was none.- catch (error) { if (!actions.error(error) && !note.textContent) say(t('Could not start. Try again.', '没能开始,请重试。')); }+ // A specific reason is said once; the planning limits are already shown above.+ catch (error) { const result = actions.error(error, 'generate'); if (result?.say && !['chain_too_long', 'chain_part_too_short'].includes(result.reason)) say(result.say);+ else if (!result && !note.textContent) say(t('Could not start. Try again.', '没能开始,请重试。')); }finally { pressing.delete(key); render(); }};cancel.onclick = () => (!previewSelection && actions.selectionHeld?.() ? Promise.resolve(actions.unhold()).then(render) : actions.cancel()).catch(actions.error);- resume.onclick = () => actions.resume().catch(actions.error);+ resume.onclick = () => actions.resume().catch(value => actions.error(value, 'generate'));const unsubscribe = state.subscribe(event => {if (event.type === 'selection' && state.selection?.kind === 'range') {if (state.rangeText === null) state.setRangeText(input.value);@@ -117,7 +144,7 @@ export function createEditorGenbar(host, {state, t, actions, text = ''}) {if (event.type === 'selection' || event.type === 'record') render();});render();- return {element: host, say, getText() { return input.value; }, update(value) { status = value; render(); }, preview(selection) { previewSelection = selection; render(); }, setText(value) { input.value = value || ''; state.setRangeText(input.value); render(); },+ return {element: host, say, downloadFailure, getText() { return input.value; }, update(value) { status = value; render(); }, preview(selection) { previewSelection = selection; render(); }, setText(value) { input.value = value || ''; state.setRangeText(input.value); render(); },dispose() { disposed = true; ++serial; clearTimeout(noteTimer); unsubscribe(); references?.dispose(); }};}diff --git a/web/editor_library.js b/web/editor_library.jsindex 3b52db3..3d18540 100644--- a/web/editor_library.js+++ b/web/editor_library.js@@ -19,7 +19,9 @@ export function createEditorLibrary(host, {store, t, actions, state}) {let tab = 'work', rows = [], imported = [], next = null, disposed = false, loading = false;let listRead = Promise.resolve(), refreshTask = null, retryTimer = null, finishRetry = null, refreshAgain = false;const expectedOutputs = new Set();- const uploading = new Map(), recentImports = new Map();+ const uploading = new Map(), recentImports = new Map(), pendingAdds = new Map();+ const preparing = () => t('Preparing this clip. It goes on the timeline when ready.', '素材正在准备,准备好后会自动放到时间线上。');+ const cannotOpen = () => t('This file cannot be opened. Supported formats: ', '这个文件打不开。支持的格式:') + FORMATS;function metadata(row, kind) {const g = row.geometry || row, cached = store.sources.get(`${kind}:${row.id}`);return {frames: cached?.frames || Math.round(g.frames || (g.seconds || 0) * (g.fps || 24)), hasVideo: cached?.has_video ?? (kind === 'work' || row.kind === 'video'),@@ -27,22 +29,42 @@ export function createEditorLibrary(host, {store, t, actions, state}) {}// The "+" puts a video after the last picture and a sound at the play position;// a double click leaves the place to the page, which appends.- async function add(row, kind, plus = false) {+ async function add(row, kind, plus = false, {queued = false, project = actions.projectToken?.()} = {}) {const source = {kind, id: row.id}, key = sourceKey(source), playhead = state?.playhead;await store.getSources([key]);- if (disposed) return;+ if (disposed || project != null && project !== actions.projectToken?.()) return;const value = store.sources.get(key), fallback = metadata(row, kind), hasVideo = value?.has_video ?? fallback.hasVideo;const pictures = state?.record.tracks.find(track => track.id === 'v1')?.clips || [];const at = !plus || !state ? undefined : hasVideo ? Math.max(0, ...pictures.map(clip => clip.start + clip.frames)) : playhead;- await actions.insertSource({source, at, frames: value?.frames || fallback.frames,+ const result = await actions.insertSource({source, at, frames: value?.frames || fallback.frames,hasVideo, hasAudio: value?.has_audio ?? fallback.hasAudio});+ if (queued && !disposed && result?.ok !== false) actions.notify?.(t('Added to the timeline.', '已放到时间线上。'));+ }+ function requestAdd(row, kind, plus = false) {+ if (disposed) return;+ if (kind === 'work' || row.state === 'ready') return add(row, kind, plus).catch(actions.error);+ if (row.state === 'failed') { actions.notify?.(cannotOpen()); return; }+ const key = `${kind}:${row.id}`;+ if (!pendingAdds.has(key)) pendingAdds.set(key, {plus, project: actions.projectToken?.()});+ actions.notify?.(preparing());+ }+ function startPending(items) {+ for (const row of items) {+ const key = `import:${row.id}`, pending = pendingAdds.get(key);+ if (!pending) continue;+ if (pending.project != null && pending.project !== actions.projectToken?.()) { pendingAdds.delete(key); continue; }+ if (row.state === 'ready') {+ pendingAdds.delete(key);+ add(row, 'import', pending.plus, {...pending, queued: true}).catch(actions.error);+ } else if (row.state === 'failed') { pendingAdds.delete(key); actions.notify?.(cannotOpen()); }+ }}function card(row, kind) {const container = el('div', 'fv-ed-source-card');const button = el('button', 'fv-ed-source'); button.type = 'button'; button.dataset.key = `${kind}:${row.id}`;const ready = kind === 'work' || row.state === 'ready';const label = row.name || row.text || new Date(row.created_at).toLocaleDateString();- button.setAttribute('aria-label', label); button.draggable = ready; button.disabled = !ready;+ button.setAttribute('aria-label', label); button.draggable = ready; button.disabled = false;const picture = el('div', 'fv-ed-source-picture');const url = kind === 'work' ? (store.sources.get(`work:${row.id}`)?.thumbnail|| '/freevideo/library/thumbnail?' + new URLSearchParams({id: row.id})) : row.thumbnail;@@ -51,11 +73,12 @@ export function createEditorLibrary(host, {store, t, actions, state}) {if (ready) picture.append(el('span', 'fv-ed-source-time', stamp(metadata(row, kind).frames)));else if (row.state === 'failed') {picture.append(el('span', 'fv-ed-source-preparing', t('Cannot open', '打不开')));- } else picture.append(el('span', 'fv-ed-source-preparing', `${Math.round((row.fraction || 0) * 100)}%`));+ } else picture.append(el('span', 'fv-ed-source-preparing', t('Preparing', '准备中')+ + (Number.isFinite(row.fraction) ? ` ${Math.round(Math.max(0, Math.min(1, row.fraction)) * 100)}%` : '')));button.append(picture);const used = el('span', 'fv-ed-source-used'); used.append(editorIcon('check')); used.setAttribute('aria-label', t('Used', '已用')); used.hidden = true; picture.append(used);- button.ondblclick = () => add(row, kind).catch(actions.error);- button.onkeydown = event => { if (event.key === 'Enter') { event.preventDefault(); add(row, kind).catch(actions.error); } };+ button.ondblclick = () => requestAdd(row, kind);+ button.onkeydown = event => { if (event.key === 'Enter') { event.preventDefault(); requestAdd(row, kind); } };button.ondragstart = event => {if (!ready) { event.preventDefault(); return; }const value = metadata(row, kind), key = `${kind}:${row.id}`;@@ -64,10 +87,10 @@ export function createEditorLibrary(host, {store, t, actions, state}) {store.getSources([key]).catch(actions.error);};// Single click previews the source; double click also inserts it.- button.onclick = () => { if (ready) Promise.resolve().then(() => actions.previewSource?.({kind, id: row.id})).catch(actions.error); };- const plus = el('button', 'fv-ed-source-add', '+'); plus.type = 'button'; plus.disabled = !ready;+ button.onclick = () => { if (ready) Promise.resolve().then(() => actions.previewSource?.({kind, id: row.id})).catch(actions.error); else requestAdd(row, kind); };+ const plus = el('button', 'fv-ed-source-add', '+'); plus.type = 'button'; plus.disabled = button.disabled; plus.title = button.title;plus.setAttribute('aria-label', `${t('Add to the tracks', '加到轨道上')}: ${label}`);- const insert = event => { event.preventDefault(); event.stopPropagation(); if (ready && !(event.detail > 1)) add(row, kind, true).catch(actions.error); };+ const insert = event => { event.preventDefault(); event.stopPropagation(); if (!(event.detail > 1)) requestAdd(row, kind, true); };plus.onclick = insert;plus.ondblclick = event => { event.preventDefault(); event.stopPropagation(); };plus.onkeydown = event => { if (event.key === 'Enter' || event.key === ' ') insert(event); };@@ -190,12 +213,16 @@ export function createEditorLibrary(host, {store, t, actions, state}) {try {const item = await store.upload(value, fraction => { row.fraction = fraction; render(); });if (item && !disposed) {+ const pending = pendingAdds.get(`import:${id}`);+ pendingAdds.delete(`import:${id}`);+ if (pending) pendingAdds.set(`import:${item.id}`, pending);recentImports.set(item.id, item);imported = [item, ...imported.filter(existing => existing.id !== item.id)];if (place) { placing.push({id: item.id, place}); placeReady(imported); }+ else startPending([item]);}- } catch { actions.notify(t('This file cannot be opened. Supported formats: ', '这个文件打不开。支持的格式:') + FORMATS); }- finally { uploading.delete(id); render(); }+ } catch { actions.notify(cannotOpen()); }+ finally { pendingAdds.delete(`import:${id}`); uploading.delete(id); render(); }}}file.onchange = () => { importFiles([...file.files]); file.value = ''; };@@ -203,9 +230,9 @@ export function createEditorLibrary(host, {store, t, actions, state}) {for (const item of items) recentImports.delete(item.id);// A list request started before an upload may finish after it.imported = [...recentImports.values(), ...items]; render();- placeReady(imported);+ placeReady(imported); startPending(imported);});const stopUsed = state?.subscribe(event => { if (event.type === 'record') updateUsed(); });render(); load();- return {element: host, importFiles, refresh, dispose() { disposed = true; host.removeEventListener('scroll', scheduleMore); resize.disconnect(); cancelAnimationFrame(moreFrame); stop(); stopUsed?.(); clearTimeout(retryTimer); finishRetry?.(); }};+ return {element: host, importFiles, refresh, dispose() { disposed = true; pendingAdds.clear(); host.removeEventListener('scroll', scheduleMore); resize.disconnect(); cancelAnimationFrame(moreFrame); stop(); stopUsed?.(); clearTimeout(retryTimer); finishRetry?.(); }};}diff --git a/web/editor_store.js b/web/editor_store.jsindex 8592382..ea90d2c 100644--- a/web/editor_store.js+++ b/web/editor_store.js@@ -417,12 +417,13 @@ export function createEditorStore(api, {t = en => en, notify = () => {}, onGenernotice('generate', 'Restart FreeVideo to generate.', '请重新启动 FreeVideo 后再生成。');return null;}- if (response.status === 400) {+ if (!response.ok) {// The server's own sentence for a video with too many parts, or a continued part too short, is shown as it is.const body = await response.json().catch(() => null);if (['chain_too_long', 'chain_part_too_short'].includes(body?.code)) throw Object.assign(new Error(body.code), {code: body.code, said: [body.error, body.error_zh]});+ throw Object.assign(new Error(typeof body?.error === 'string' ? body.error : body?.message || `HTTP ${response.status}`),+ {status: response.status, reason: body?.reason || body?.code, response: body});}- if (!response.ok) throw errorFor(response);return (await response.json())?.chain || null;},async chain(id) { return standIn?.owns(id) ? standIn.chain(id) : (await json(chainRoute(id)))?.chain || null; },@@ -433,8 +434,11 @@ export function createEditorStore(api, {t = en => en, notify = () => {}, onGenerreturn (await json(chainRoute(id, action), post(payload)))?.chain || null;},async export(id, revision, options) {- const value = await json('/freevideo/editor/export', post({id, revision, ...(options && Object.keys(options).length ? {options} : {})}));- if (!value) notice('export', 'Export is unavailable until you restart after updating.', '更新后重启即可导出。');+ const response = await request('/freevideo/editor/export', post({id, revision, ...(options && Object.keys(options).length ? {options} : {})}));+ const value = await response.json().catch(() => null);+ if (!response.ok && (response.status !== 404 || value?.reason || value?.code))+ throw Object.assign(errorFor(response), {reason: value?.reason, code: value?.code, items: value?.items});+ if (response.status === 404 || !value) { notice('export', 'To export, update FreeVideo and restart it.', '请更新 FreeVideo 并重新启动后再导出。'); return null; }return value?.export || null;},watchExport(id, fn) { return watch(async () => (await json('/freevideo/editor/export?' + new URLSearchParams({id})))?.export || null, fn); },diff --git a/web/editor_tracks.css b/web/editor_tracks.cssindex bbd6ece..a816122 100644--- a/web/editor_tracks.css+++ b/web/editor_tracks.css@@ -39,6 +39,7 @@.fv-ed-clip[data-state=failed]{border:1px solid color-mix(in srgb,var(--fv-warning) 60%,transparent);background:color-mix(in srgb,var(--fv-warning) 12%,transparent);cursor:grab}.fv-ed-clip-status{position:absolute;left:10px;right:4px;top:50%;transform:translateY(-50%);display:flex;align-items:center;gap:4px;font-size:12px;white-space:nowrap;overflow:hidden;color:var(--fv-warning);pointer-events:none}.fv-ed-clip-status svg{width:12px;height:12px;flex:none;fill:none;stroke:currentColor;stroke-width:1.5;stroke-linecap:round}+.fv-ed-clip-failure-reason{overflow:hidden;text-overflow:ellipsis}.fv-ed-clip[data-busy=true]{cursor:default}.fv-ed-trim-handle{position:absolute;top:50%;width:4px;height:20px;border-radius:2px;transform:translateY(-50%);background:var(--fv-accent);cursor:ew-resize;z-index:2;opacity:0;pointer-events:auto}.fv-ed-trim-start{left:-2px}@@ -66,9 +67,11 @@.fv-ed-zoom-slider{width:64px;height:24px;margin:0;accent-color:var(--fv-accent);cursor:pointer}.fv-ed-track-zoom .fv-ed-fit{padding:0 7px;white-space:nowrap;font-size:12px;margin-left:4px}.fv-ed-drag-label{position:absolute;z-index:9;padding:4px 7px;background:var(--fv-card);color:var(--fv-ink);border:1px solid var(--fv-border);border-radius:6px;font-size:12px;white-space:pre;line-height:1.5;pointer-events:none}-.fv-ed-clip-popover{position:absolute;z-index:10;width:240px;max-width:calc(100% - 16px);padding:10px;border:1px solid var(--fv-border);border-radius:8px;background:var(--fv-card)}+.fv-ed-clip-popover{position:absolute;z-index:10;width:280px;max-width:calc(100% - 16px);padding:10px;border:1px solid var(--fv-border);border-radius:8px;background:var(--fv-card)}.fv-ed-clip-popover p{margin:0 0 8px;font-size:13px}.fv-ed-clip-popover button{min-height:32px;padding:4px 10px;border:1px solid var(--fv-border);border-radius:8px;background:var(--fv-raised);cursor:pointer}+.fv-ed-clip-popover button+button{margin-left:6px}+.fv-ed-clip-popover{max-height:calc(100% - 16px);overflow:auto}.fv-ed-track-view [hidden]{display:none!important}@media(max-width:520px){.fv-ed-track-view{--fv-ed-head-width:32px}.fv-ed-track-head span{display:none}.fv-ed-track-zoom{right:8px}.fv-ed-clip-status{left:5px;font-size:11px}}@media(forced-colors:active){.fv-ed-clip,.fv-ed-selection,.fv-ed-gesture-preview{border-color:Highlight}.fv-ed-playhead,.fv-ed-snap-line{background:CanvasText}}diff --git a/web/editor_tracks.js b/web/editor_tracks.jsindex 0ca0688..2ee0920 100644--- a/web/editor_tracks.js+++ b/web/editor_tracks.js@@ -163,6 +163,7 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions =const tooltip = create('div', 'fv-ed-drag-label');tooltip.hidden = true; tooltip.setAttribute('role', 'status');const popover = create('div', 'fv-ed-clip-popover'); popover.hidden = true;+ let failedPopoverId = null;const zoomBar = create('div', 'fv-ed-track-zoom fv-ed-zoom');const zoomOut = create('button', '', '−'), zoomIn = create('button', '', '+');zoomOut.type = zoomIn.type = 'button';@@ -443,6 +444,7 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions =item.component?.update(value);}function renderRecord() {+ const openFailure = !popover.hidden && failedPopoverId;selectGestures.finish(null, true);cachedPlan = ''; popover.hidden = true;const record = state.record, retained = new Set(), tracks = displayTracks(record);@@ -496,10 +498,11 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions =&& (right.pending === null || model.continuesBefore(state.record, right.id));item.element.classList.toggle('fv-ed-joined-left', attached(track.clips[index - 1], clip));item.element.classList.toggle('fv-ed-joined-right', attached(clip, track.clips[index + 1]));- if (visual === 'failed' && track.kind === 'video') item.status.replaceChildren(icon('warning'));+ const failureText = visual === 'failed' ? actions.failureText?.(clip.id) || actions.reasonText?.(clip.reason) || clip.reason || t('Generation failed', '生成时出错') : '';+ if (visual === 'failed') item.status.replaceChildren(icon('warning'), create('span', 'fv-ed-clip-failure-reason', failureText));else item.status.replaceChildren();const status = {planned: t('Not generated yet', '还没生成'), running: t('Generating', '正在生成'),- done: t('Complete', '完成'), failed: t('Unsuccessful', '没成功')}[visual];+ done: t('Complete', '完成'), failed: failureText}[visual];const seconds = Math.round(clip.frames / model.FPS);item.element.title = '';item.element.setAttribute('aria-label', t(`${name}, clip ${index + 1}, ${seconds} s, ${status}`,@@ -526,6 +529,8 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions =addAudio.setAttribute('aria-label', addAudio.textContent);content.style.height = `${top - 6}px`; playhead.style.height = `${top - 24}px`;layout();+ const failure = openFailure && clips.get(openFailure);+ if (failure && model.clipState(failure.clip) === 'failed' && state.selection?.ids?.includes(openFailure)) failedPopover(failure);if (gesture?.type === 'move' && pointerEvent) updatePointer(pointerEvent);}function showGuide(frame) { guide.hidden = frame == null; if (frame != null) guide.style.left = `${pixels(frame)}px`; }@@ -563,14 +568,18 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions =renderSelection();}function failedPopover(item) {- const reason = create('p', '', actions.reasonText?.(item.clip.reason) || t('Could not generate', '没能生成'));+ failedPopoverId = item.clip.id;+ const reason = create('p', '', actions.failureText?.(item.clip.id) || actions.reasonText?.(item.clip.reason) || item.clip.reason || t('Generation failed', '生成时出错'));+ const report = create('button', 'fv-ed-clip-report', t('Download diagnostic report', '下载诊断报告')); report.type = 'button';+ report.onclick = event => { event.stopPropagation(); popover.hidden = true;+ Promise.resolve(actions.downloadFailure?.(item.clip.id)).catch(error => actions.editError?.(error)); };const retry = create('button', '', t('Retry', '重试')); retry.type = 'button';retry.onclick = () => { popover.hidden = true;- Promise.resolve().then(() => actions.retry?.(item.clip.id)).catch(error => actions.editError?.(error)); };- popover.replaceChildren(reason, retry); popover.hidden = false;+ Promise.resolve().then(() => actions.retry?.(item.clip.id)).catch(error => actions.editError?.(error, 'generate')); };+ popover.replaceChildren(reason, report, retry); popover.hidden = false;const bounds = element.getBoundingClientRect(), clipBounds = item.element.getBoundingClientRect();- popover.style.left = `${clamp(clipBounds.left - bounds.left, 8, Math.max(8, bounds.width - 248))}px`;- popover.style.top = `${Math.min(clipBounds.bottom - bounds.top + 4, bounds.height - 96)}px`;+ popover.style.left = `${clamp(clipBounds.left - bounds.left, 8, Math.max(8, bounds.width - 288))}px`;+ popover.style.top = `${Math.max(8, Math.min(clipBounds.bottom - bounds.top + 4, bounds.height - popover.getBoundingClientRect().height - 8))}px`;}function clickSelection(event) {if (event.range) return;diff --git a/web/health.js b/web/health.jsindex 0398774..8e04ae5 100644--- a/web/health.js+++ b/web/health.js@@ -14,7 +14,7 @@ const t = (en, zh) => cn ? zh : en;const launchVisit = query.get('freevideo') === 'launch';// Every script this folder ships; a test keeps the list in step with web/*.js.export const MODULES = ['agent_activity.js', 'agent_connect.js', 'agent_session.js', 'autopilot.js', 'autopilot_chat.js', 'autopilot_conversations.js', 'browser_extension.js', 'chain_support.js', 'capability_view.js', 'compatibility.js', 'error_panel.js', 'first_run_guide.js', 'fonts.js', 'freevideo.js', 'generation_progress.js',- 'editor.js', 'editor_actions.js', 'editor_adjust.js', 'editor_adjust_picture.js', 'editor_picture_fields.js', 'editor_picture_session.js', 'editor_preview_picture.js', 'editor_entry.js', 'editor_export_dialog.js', 'editor_first_frame.js', 'editor_media_references.js', 'editor_references.js', 'editor_genbar.js', 'editor_geometry.js', 'editor_library.js', 'editor_menu.js', 'editor_model.js', 'editor_frame.js', 'editor_player.js', 'editor_room.js', 'editor_select.js', 'editor_state.js', 'editor_store.js', 'editor_tracks.js', 'editor_generation.js', 'editor_transport.js', 'editor_transport_model.js', 'editor_audio.js', 'editor_audio_model.js', 'editor_audio_notes.js', 'editor_audio_replace.js', 'editor_audio_rules.js', 'editor_speed.js', 'editor_speed_model.js',+ 'editor.js', 'editor_actions.js', 'editor_adjust.js', 'editor_adjust_picture.js', 'editor_picture_fields.js', 'editor_picture_session.js', 'editor_preview_picture.js', 'editor_entry.js', 'editor_export_dialog.js', 'editor_first_frame.js', 'editor_media_references.js', 'editor_references.js', 'editor_genbar.js', 'editor_geometry.js', 'editor_library.js', 'editor_menu.js', 'editor_model.js', 'editor_frame.js', 'editor_player.js', 'editor_room.js', 'editor_select.js', 'editor_state.js', 'editor_store.js', 'editor_tracks.js', 'editor_generation.js', 'editor_transport.js', 'editor_transport_model.js', 'editor_audio.js', 'editor_audio_model.js', 'editor_audio_notes.js', 'editor_audio_replace.js', 'editor_audio_rules.js', 'editor_speed.js', 'editor_speed_model.js', 'editor_failure.js','editor_loader.js', 'editor_text_coverage.js', 'editor_text.js', 'editor_text_model.js', 'editor_text_layout.js', 'editor_notes.js', 'editor_icons.js', 'dialog_keys.js', 'frame_sizes.js', 'health.js', 'image_commands.js', 'image_editor.js', 'image_editor_engine.js', 'image_generation.js', 'launcher.js', 'length_plan.js', 'lora_triggers.js', 'library.js', 'motion.js', 'output_download.js', 'port_notice.js', 'preview_scene.js','progress_connection.js', 'prompt_draft.js', 'prompt_enhance.js', 'prompt_references.js', 'report_issue.js', 'studio_recent.js','result_actions.js', 'sampling_effort.js', 'setup.js', 'share.js', 'share_layout.js', 'studio.js', 'studio_chain.js', 'studio_extend.js', 'studio_length.js', 'first_frame_row.js', 'optional_inputs.js', 'studio_queue.js', 'studio_size.js',